4 ms·
If you don't want to think about binding, just use the arrow function syntax: class Foo extends Component { bar = () => { // ... }
by tlrobinson 10y ago
If you don't want to think about binding, just use the arrow function syntax:
class Foo extends Component {
bar = () => {
// ...
}
}
- acemarke 10y agoRequires the Stage 2 Class Properties syntax to be enabled (via Babel plugin), but yes, that's the "nicest" way to do it, and the current approach recommended by the React team. There's also various binding utilities, like https://github.com/cassiozen/React-autobind https://github.com/cassiozen/React-autobind . I've got discussion of the various binding approaches listed at https://github.com/markerikson/react-redux-links/blob/master/using-react-with-es6.md https://github.com/markerikson/react-redux-links/blob/master... .
- amk_ 10y agoI use and recommend this syntax, but you do have to have babel-preset-stage-2 to enable the class properties transform. https://babeljs.io/docs/plugins/transform-class-properties/ https://babeljs.io/docs/plugins/transform-class-properties/
- TheSisb2 10y agoThis compiles poorly and has a performance cost, it turns out. Doing: constructor(props) { super(props); this.func = this.func.bind(this); } Is better if you care about performance.
- ConAntonakos 10y agoJust curious: are there tests proving this?