我浏览了与我的问题略相关的活跃问题,但没有得到成功的解决方案。我希望有一个人可以帮助我。
我在js小提琴上有一个简单的React Baby代码:http : //jsfiddle.net/kb3gN/10313/
我的代码的解释可以在下面的代码中找到:
var Test = React.createClass({
getInitialState: function(){
return{
data: [
['Charlie', 10],
['Bello', 20],
['Wuffi', 15]
]
}
},
render: function(){
return(
<div>
<MakePOS data={this.state.data} />
<MakeTable />
</div>
);
}
});
var MakeTable = React.createClass({
getInitialState: function(){
return{
active: 0,
weight: 0
}
},
render: function(){
return(
<table>
<thead>
<tr>
<td>Type</td>
<td>Amount</td>
</tr>
</thead>
<tbody>
<tr>
<td>Chicken</td>
<td>some</td>
</tr>
<tr>
<td>Carotts</td>
<td>some</td>
</tr>
<tr>
<td>Apple</td>
<td>some</td>
</tr>
</tbody>
</table>
);
}
});
var MakePOS = React.createClass({
handleClick: function(){
// update state of MakeTable Component to active = id of the clicked element
// also update state of MakeTable Component to weight = data-weight value
},
render: function(){
var POS = this.props.data.map(function(i){
console.log(i[0]+' '+i[1]+' kg');
return <button onClick={this.handleClick} data-weight={i[1]} id={i[0]}>{i[0]}</button>;
});
return(<div className="testDiv">{POS}</div>);
}
});
React.render(<Test />, document.getElementById('foodApp'));
解释我的代码:
测试组件中的状态数组代表用户输入,在这种情况下,他选择填写3只宠物及其体重。
在MakePOS组件中动态创建按钮以进行输入。
现在,我要做的是处理这些按钮上的Click事件,并影响MakeTable组件的状态,以便处理隐藏在该按钮后面的值。
我想根据宠物的体重来动态更改表格的行数。
我希望它是可以理解的。
谢谢你的帮助
编辑Facebook文档中提到了类似的内容,但是我并没有真正得到它的提示。在他们的示例中,他们只是在同一组件中调用onClick函数。我找不到更改父组件的子组件状态的任何解决方案:( http://facebook.github.io/react/tips/communicate-between-components.html
handleClick
在这种情况下Test
,您应该将函数移动到管理要影响状态的组件,然后通过props将其作为回调传递。由于点击也会影响active
和weight
,因此它们也应保持在的状态Test
,因此handleClick
可以轻松更改其状态。
var Test = React.createClass({
getInitialState: function(){
return{
data: [
['Charlie', 10],
['Bello', 20],
['Wuffi', 15]
],
active: 0,
weight: 0
}
},
changeWeight: function(weight){
// do whatever actions you want on click here
console.log('I am in the main Component ');
console.log(weight);
},
render: function(){
return(
<div>
<MakePOS data={this.state.data} changeWeight={this.changeWeight} />
<MakeTable active={this.state.active} weight={this.state.weight}/>
</div>
);
}
});
var MakeTable = React.createClass({
getInitialState: function(){
return{
active: 0,
weight: 0
}
},
render: function(){
return(
<table>
<thead>
<tr>
<td>Type</td>
<td>Amount</td>
</tr>
</thead>
<tbody>
<tr>
<td>Chicken</td>
<td>some</td>
</tr>
<tr>
<td>Carotts</td>
<td>some</td>
</tr>
<tr>
<td>Apple</td>
<td>some</td>
</tr>
</tbody>
</table>
);
}
});
var MakePOS = React.createClass({
handleClick: function(weight){
this.props.changeWeight(weight);
},
render: function(){
var POS = this.props.data.map(function(i){
console.log(i[0]+' '+i[1]+' kg');
return <button onClick={this.handleClick.bind(this,i[1])} key={i[0]} id={i[0]}>{i[0]}</button>;
}.bind(this));
return(<div className="testDiv">{POS}</div>);
}
});
React.render(<Test />, document.getElementById('foodApp'));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句