我想在警报窗口中显示人员的电子邮件。但是,我不知道如何将电子邮件作为参数传递给 displayAlert 方法。此外,它也不会让我使用。因此,我必须将 displayAlert 方法分配给一个变量并在 onClick 中使用它。我不知道为什么它不会让我直接调用它。
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> ); } }
如何将参数传递给 React js 中的函数?
IT技术
reactjs
                    2021-05-05 02:41:12
                
                    
                
            
        2个回答
            ES6方式:
使用箭头函数 =>
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 匿名函数被调用并执行 this.displayAlert(item.email)
ES5方式:
您可以使用.bind并在其中传递参数来执行此操作。
您还应该传递this或使用 bind 来保持.map函数的正确上下文:
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);
在这里的示例中显示:React - 组件之间的通信
使用箭头函数和 babel 插件“transform-class-properties”
class People extends React.Component {
  render() {
    return (
      <ul>
        { this.props.items.map( (item) => (
          <li key={item.id}>
            <button onClick={this.displayAlert(item)}>
              {item.lastName + ', ' + item.firstName}
            </button>
          </li>
        ))}
      </ul>
    )
  }
  displayAlert = (item) => (event) => {
    // you can access the item object and the event object
    alert('Hi');
  }
}
其它你可能感兴趣的问题