Skip to content

Instantly share code, notes, and snippets.

@wuct
Last active January 28, 2016 02:49
Show Gist options
  • Save wuct/ba186e3c882a188a2064 to your computer and use it in GitHub Desktop.
Save wuct/ba186e3c882a188a2064 to your computer and use it in GitHub Desktop.
How to bind methods in React components
// 在 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