【发布时间】:2017-01-30 04:42:52
【问题描述】:
我在一些网站上发现关于 react autobindig 的矛盾,例如:
第一个链接做手动自动绑定 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 });
}
}
第二个链接做自动 http://buildwithreact.com/tutorial/state
在最后一个链接上:
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')
"注意:自动绑定 您可能会惊讶我们不需要将回调作为 this.onCowClick.bind(this) 传递。 (如果没有,请阅读此内容)。这是因为 React 出于性能原因自动绑定组件实例上的方法。在这里阅读更多内容。”
React 自动绑定?如果答案是“是”,有时您需要在某些情况下使用 onclick 手动绑定??
【问题讨论】:
-
如果你使用 createClass,react 会自动绑定。您无需手动操作。
-
谢谢,我已经更新了我的答案,第一个代码链接,手册,为什么?谢谢
标签: reactjs