React implements event handling in the following ways

First: use the bind method in the constructor function

class ReactEvent extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log('Click'); } render() { return <button onClick={this.handleClick}>Click Me</button>; }}Copy the code

Render arrow function (render arrow function)

class ReactEvent extends Component { handleClick() { console.log('Click'); } render() { return <button onClick={() => this.handleClick()}>Click Me</button>; }}Copy the code

Third: use the class fields syntax

class ReactEvent extends Component { handleClick = () => { console.log('Click'); } render() { return <button onClick={this.handleClick}>Click Me</button>; }}Copy the code

Fourth: use bind in render

class ReactEvent extends Component { handleClick() { console.log('Click'); } render() { return <button onClick={this.handleClick.bind(this)}>Click Me</button>; }}Copy the code

Several ways to compare

impact Bind in the constructor function Use the Class fields syntax Use the arrow function in render Use bind in render
Render generates a new function no no is is
performance No effect No effect Have an impact on Have an impact on
Parameters can be carried directly no no is is

The bind and arrow functions in Render create a new function each time, causing the props of the subcomponents to change. This affects performance in PureComponent. Unless you optimize it in shouldComponentUpdate.

Parameter passing

Pass arguments directly, using the arrow function in Render

      this.state.list.map(item => (
          <Button onClick={() => this.handleClick(item.id)}/>
      ))
Copy the code

Pass arguments directly, using bind in render

      this.state.list.map(item => (
          <Button onClick={this.handleClick.bind(this, item.id)}/>
      ))
Copy the code

Recommended ways

PureComponent {handleClick = () => {this.props. HandleClick (this.props. Item); Render () {return (<button onClick={this.handleclick}> Hello world</button>)}} class ButtonList extends React.Component { constructor(props) { super(props); this.state = { list: [1, 2, 3, 4] }; } handleClick = (item) => { console.log('Click', item); } render() { const { list=[] } = this.state; return ( <div> { list.map(item => <Button handleClick={this.handleClick} item={item}/>) } </div> ) } }Copy the code