方法一:最麻烦的写法,不推荐
import React from 'react'; class App extends React.Component { handleClick() { alert('点击') } render() { return ( <div> <button onClick={this.handleClick.bind(this)}>click</button> </div> ) } } export default App;
方法二:在构造函数里统一绑定,不常用。
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this) } handleClick() { alert('点击') } render() { return ( <div> <button onClick={this.handleClick}>click</button> </div> ) } } export default App;
方法三:最常见的写法。
import React from 'react'; class App extends React.Component { constructor(props) { super(props); } handleClick = () => { alert('点击') } render() { return ( <div> <button onClick={this.handleClick}>click</button> </div> ) } } export default App;
方法四:可以传参数。
import React from 'react'; class App extends React.Component { constructor(props) { super(props); } handleClick (e) { alert(e) } render() { return ( <div> <button onClick={(e) => this.handleClick(e)}>click</button> </div> ) } } export default App;