stackdave stackdave - 2 months ago 10
React JSX Question

react auto binding on click is automatic for this

I find contradictions in some sites about react autobindig, example:

first link do manual autobind
React, Binding input values

class Post extends React.Component {
constructor(props) {
super(props);

this.state = {
post: this.props.data,
comment: ''
};
}

render() {
return <div>
<input
type="text"
value={this.state.comment}
onChange={ this.handleChange.bind(this) }
placeholder="Write a comment..." />

<button
className="button comments"
onClick={ this.handleClick.bind(this, this.state.post.id)}>Button</button>
</div>
}

handleClick(postId, e) {
console.log( postId );
console.log( this.state.comment );
}

handleChange(e) {
this.setState({ comment: e.target.value });
}
}


second link do automatic
http://buildwithreact.com/tutorial/state

on the last link:

var CowClicker = React.createClass({
getInitialState: function() {
return {
clicks: 0
};
},

onCowClick: function(evt) {
this.setState({
clicks: this.state.clicks + 1
});
},

render: function() {
return (
<div>
<div>Clicks: {this.state.clicks}</div>
<img
src="http://s3.bypaulshen.com/buildwithreact/cow.png"
onClick={this.onCowClick}
className="cow"
/>
<p>Click the cow</p>
</div>
);
}
});

ReactDOM.render(
<CowClicker />,
document.getElementById('container')


"NOTE: AUTOBINDING
You may be surprised that we don't need to pass the callback as this.onCowClick.bind(this). (If not, read this). This is because React autobinds methods on the component instance for performance reasons. Read more here."

React do autobinding? if the answer is 'yes', sometimes you need to bind manually in some case with onclick ??

Answer

when you use React.createClass react do binding for you.
if you are using es6 class syntax react no more do binding for you.
it means you should manually do .bind(this).

but you can use fat arrow functions which don't define their own this value, instead they are bound to the lexical this of their current context.

check it out http://codepen.io/dagman/pen/wzgvja

class Button extends React.Component {
    handleClick = () => {
        alert('Hello World');
    };
    render() {
        return (
            <button onClick={this.handleClick}>button</button>
        );
    }
}

ReactDOM.render(
    <Button />,
    document.getElementById('mount-node')
);