Last active
January 28, 2016 02:49
-
-
Save wuct/ba186e3c882a188a2064 to your computer and use it in GitHub Desktop.
How to bind methods in React components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 在 constructor 內 bind | |
export default class extends React.Component { | |
constructor(...args) { | |
super(...args) | |
this.doSomething = this.doSomething.bind(this) | |
} | |
doSomething() {} | |
render () { | |
return <div onClick={doSomething}/> | |
} | |
} | |
// 直接用 arrow function | |
export default class extends React.Component { | |
doSomething = () => {} | |
render = () => <div onClick={doSomething}/> | |
} | |
// 如果有用 recompose,可用 withAttachedProps | |
import { withAttachedProps, compose } from 'recompose'; | |
export default compose( | |
withAttachedProps(getProps => ({ | |
doSomething: () => {} | |
})) | |
)(() => <div onClick={doSomething}/>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment