reactjs - How to pass arguments to functions in React js? -
i want display person's email in alert window. but, not know how pass email arguments displayalert method. also, wont let me use either. so, have assign displayalert methos variable , use in onclick. not know why wont let me call 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 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
anonymous function called , executes this.displayalert(item.email)
the es5 way:
you using .bind
, passing parameter in there.
you should pass this
or use bind keep proper context on .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 example here: react - communicate between components
Comments
Post a Comment