2014-11-23 32 views
5

我想從子組件傳遞道具到父組件,但由於某種原因,我得到錯誤「TypeError:this.props.onClick不是點擊渲染的子組件後,在js控制檯中顯示一個「函數」。React.js - 傳遞函數「不是函數」錯誤

基本上我想要做的是管理一個類別列表,其中一個類別子組件具有「選定」屬性爲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')); 

回答

0

顯然,這是這裏的範圍問題:

this.state.items.map(function(item){ 
      return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />; 
     }) 

如果我刪除外部映射並添加一個通用類別它的作品(好吧,還有其他問題,但點擊功能是s成功通過)。

我將不得不以另一種方式傳遞函數(通過不使用this.handleClick)。

2

可以使用綁定來解決這個問題

this.state.items.map(function(item){ 
    return <Category onClick={this.handleClick} name={item[0]} selected={item[1]} />; 
}.bind(this))