Hacker News new | ask | show | jobs
by tlrobinson 3360 days ago
If you don't want to think about binding, just use the arrow function syntax:

    class Foo extends Component {
      bar = () => {
        // ...
      }
    }
3 comments

Requires 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 . I've got discussion of the various binding approaches listed at https://github.com/markerikson/react-redux-links/blob/master... .
I 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/

This 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.

Just curious: are there tests proving this?