Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

reactjs - How to pass arguments to functions in React js?

  1. 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>
        );
      }
    }
    
question from:https://stackoverflow.com/questions/30608347/how-to-pass-arguments-to-functions-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...