react 事件綁定 函數寫法 文檔總結
https://react.docschina.org/docs/handling-events.html
1 通過 constroucor綁定
class Toggle extends React.Component {constructor(props) {super(props);this.state = {isToggleOn: true};// This binding is necessary to make `this` work in the callbackthis.handleClick = this.handleClick.bind(this);}handleClick() {this.setState(prevState => ({isToggleOn: !prevState.isToggleOn}));}render() {return (<button onClick={this.handleClick}>{this.state.isToggleOn ? 'ON' : 'OFF'}</button>);}
}
2 使用新屬性 屬性初始化器
class LoggingButton extends React.Component {// This syntax ensures `this` is bound within handleClick.// Warning: this is *experimental* syntax.handleClick = () => {console.log('this is:', this);}render() {return (<button onClick={this.handleClick}>Click me</button>);}
}
3 回調函數中使用 箭頭函數: 這樣調用方式有缺點,就是每次 LoggingButton 渲染的時候都會創建一個不同的回調函數。在大多數情況下,這沒有問題。然而如果這個回調函數作為一個屬性值傳入低階組件,這些組件可能會進行額外的重新渲染。我們通常建議在構造函數中綁定或使用屬性初始化器語法來避免這類性能問題。
class LoggingButton extends React.Component {handleClick() {console.log('this is:', this);}render() {// This syntax ensures `this` is bound within handleClickreturn (<button onClick={(e) => this.handleClick(e)}>Click me</button>);}
}