如果使用箭頭函式就可以不用在 constructor 中綁定函數,就可以直接用 this.function來使用。
Binding:
import React from 'react'; class MyComponent extends React.Component { constructor(props) { super(props) this.clickHandler = this.clickHandler.bind(this); } clickHandler() { console.log(this); } render() { return <button onClick={this.clickHandler}>Click Me</button> } }
Arrow-function:
import React from 'react'; class MyComponent extends React.Component { constructor(props) { super(props) } clickHandler = () => { console.log( this ) } render() { return <button onClick={this.clickHandler}>Click Me</button> } }
參考:
https://stackoverflow.com/questions/50375440/binding-vs-arrow-function-for-react-onclick-event
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記