bnu*_*mak 5 javascript reactjs
我试图将道具从子组件传递到父组件,但由于某种原因,我在js控制台中点击渲染的子组件后得到错误"TypeError:this.props.onClick不是函数".
基本上我要做的是管理一个类别列表,其中一个类别子组件将"selected"prop作为true,并且每次单击类别li时都会正确更新.
这是一个代码的jsfiddle:http://jsfiddle.net/kb3gN/8023/
我真的不觉得我已经掌握了如何有效地使用React.js的概念,所以任何帮助都表示赞赏!
最诚挚的问候和提前谢谢,
bnunamak
码:
var CategoryList = React.createClass({
getInitialState:function(){
return {
items:[
["cat1", false],
["cat2", true]
],
lastToggled:["cat2"]
}
},
//Function passed to child (changes items state)
handleClick:function(child){
var tempItems = this.state.items;
if(this.state.lastToggled[0] === child.props.name){
var index = this.getInd(this.state.tempItems, child.props.name);
tempItems[index][1] = !tempItems[index][1];
this.setState({items: tempItems});
}else{
var newIndex = this.getInd(this.state.tempItems, child.props.name);
tempItems[newIndex][1] = !tempItems[newIndex][1];
var oldIndex = this.getInd(this.state.tempItems, this.state.lastToggled[0]);
tempItems[oldIndex][1] = false;
this.setState({items: tempItems, lastToggled: tempItems[newIndex][0]});
}
},
//getInd not relevant to problem
getInd:function(arr, elname){
for (var i = arr.length - 1; i >= 0; i--) {
if(arr[i][0] === elname){
return i;
}
};
return -1;
},
render:function(){
return (<ul className="category-list">
{
this.state.items.map(function(item){
return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />;
})
}
</ul>)
}
});
var Category = React.createClass({
render:function(){
if(this.props.selected){
return (<li onClick={this.propogateClick} className="selected">{this.props.name}</li>);
}else{
return (<li onClick={this.propogateClick}>{this.props.name}</li>);
}
},
propogateClick: function(){
this.props.onClick(this);
}
});
React.renderComponent(<CategoryList/>, document.getElementById('example'));
Run Code Online (Sandbox Code Playgroud)
显然这是一个范围问题:
this.state.items.map(function(item){
return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />;
})
Run Code Online (Sandbox Code Playgroud)
如果我删除外部地图并添加通用类别,它就可以工作(好吧,还有其他问题,但单击功能已成功通过)。
我将不得不以另一种方式传递该函数(不使用 this.handleClick)。
| 归档时间: |
|
| 查看次数: |
7826 次 |
| 最近记录: |