【发布时间】:2015-04-07 18:14:23
【问题描述】:
不确定我是否理解正确。如果我正在制作一个子组件,键入按钮,它会增加自己的计数器,是否可以在没有 2 个单独功能的情况下这样做?以下我所做的似乎是一个黑客?如果有 X 数量的按钮,我将如何重构此代码以使其更具动态性? REF 似乎以我可以在孩子中引用 html 的方式工作,但另一种方式呢?我什至认为这是正确的方法,因为组件有自己的状态,它应该有自己的更新方法吗?
/*** @jsx React.DOM */
var MyComponent = React.createClass({
getInitialState: function() {
return {
counter1: 1,
counter2: 1
};
},
increment: function(i) {
if (i === 1) {
this.setState({
counter1: this.state.counter1 + 1
});
} else {
this.setState({
counter2: this.state.counter2 + 1
});
}
},
render: function() {
return ( < div >
<ChildComponent item = {this.state.counter1} click={this.increment.bind(this, 1)}/>
<ChildComponent item={this.state.counter2} click={this.increment.bind(this, 2)}/ >
< /div>
);
}
});
var ChildComponent = React.createClass({
render: function() {
return (
<div>
<h1> Counter {this.props.item} </h1 >
<button onClick = {this.props.click} > ++ < /button>
</div >
);
}
});
React.render( < MyComponent / > , document.body);
【问题讨论】:
-
对不起,我不清楚这个问题。你说的 2 个单独的函数叫什么名字?
-
如果每个孩子都有一个增量函数,即增量 1 和增量 2,我想我以错误的方式解决了这个问题。我认为每个 ChildComponent 都应该有自己的增量功能。解决方案 = gist.github.com/antigirl/90f46aa7f51ba05f676a ?
标签: javascript events components state reactjs