[英]React.js - Passed function “not a function” Error
我试图将道具从子组件传递到父组件,但由于某种原因,我在点击渲染的子组件后,在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'));
您可以使用bind来解决此问题
this.state.items.map(function(item){
return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />;
}.bind(this))
显然这是一个范围问题:
this.state.items.map(function(item){
return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />;
})
如果我删除外部地图并添加一个通用类别它是有效的(好吧,还有其他问题,但点击功能已成功通过)。
我将不得不以另一种方式传递函数(通过不使用this.handleClick)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.