如何将参数传递给 React js 中的函数? [英] How to pass arguments to functions in React js?
问题描述
我想在警报窗口中显示某人的电子邮件.但是,我不知道如何将电子邮件作为参数传递给 displayAlert 方法.此外,它也不会让我使用.因此,我必须将 displayAlert 方法分配给一个变量并在 onClick 中使用它.我不知道为什么它不会让我直接调用它.
class People 扩展 React.Component{使成为 (){var handleClick = this.displayAlert;var items = this.props.items.map(function(item) {返回(<ul key = {item.id}><li><button onClick= {handleClick}>{item.lastName + ', ' + item.firstName}</button>
)});返回 (
);}显示警报(){警报('你好');}}类 PersonList 扩展了 React.Component{使成为 () {返回 (<div><人物物品={this.props.people}/>/* 人是一组人*/
);}}
ES6方式:
使用箭头函数=>
const items = this.props.items.map((item) => (<ul key={item.id}><li><button onClick={() =>this.displayAlert(item.email)}>{item.lastName + ', ' + item.firstName}按钮>));
onClick
匿名函数被调用并执行this.displayAlert(item.email)
ES5 方式:
您可以使用 .bind
并在那里传递参数.
您还应该传递 this
或使用 bind 来保持 .map
函数的正确上下文:
var items = this.props.items.map(function(item) {返回 (<ul key={item.id}><li><button onClick={this.displayAlert.bind(this, item.email)}>{item.lastName + ', ' + item.firstName}按钮>);}, 这);
显示在此处的示例中:React - 组件之间的通信
I want to display person's email in the alert window. But, I do not know how to pass email as arguments to displayAlert method. Also, it wont let me use either. So, I have to assign displayAlert methos to a variable and use it in onClick. I do not know why it wont let me call it directly.
class People extends React.Component{ render (){ var handleClick = this.displayAlert; var items = this.props.items.map(function(item) { return( <ul key = {item.id}> <li> <button onClick= {handleClick}>{item.lastName + ', ' + item.firstName}</button> </li> </ul> ) }); return (<div>{items}</div>); } displayAlert (){ alert('Hi'); } } class PersonList extends React.Component{ render () { return ( <div> <People items={this.props.people}/> /* People is an array of people*/ </div> ); } }
The ES6 way:
Using arrow functions =>
const items = this.props.items.map((item) => (
<ul key={item.id}>
<li>
<button onClick={() => this.displayAlert(item.email)}>
{item.lastName + ', ' + item.firstName}
</button>
</li>
</ul>
));
onClick
the anonymous function is called and executes this.displayAlert(item.email)
The ES5 way:
You could do this using .bind
and passing the parameter in there.
You should also pass this
or use bind to keep the proper context on your .map
function:
var items = this.props.items.map(function(item) {
return (
<ul key={item.id}>
<li>
<button onClick={this.displayAlert.bind(this, item.email)}>
{item.lastName + ', ' + item.firstName}
</button>
</li>
</ul>
);
}, this);
Shown in the example here: React - Communicate Between Components
这篇关于如何将参数传递给 React js 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!