2016-12-01 65 views
0

我正在嘗試創建一個表並呈現一些具有「隱藏」行能力的行。在React中創建onClick事件

這裏是我想要做的事:

var Child = React.createClass({ 
    render: function() { 
     return(
      <tr> 
       <td colSpan="8"> I am a child that can be hidden!</td> 
      </tr> 
     ) 
    } 
}) 


var CreateRows = React.createClass({ 
    getInitialState: function() { 
     return {childVisible: true} 
    }, 

    render: function(){ 
     var rows = this.props.people.map(function(row, i){ 
      return (
       <tr key={i} onClick={this.onClick}>  
        <td>{row['id']}</td> 
       </tr> 
       { 
        this.state.childVisible 
        ? <Child /> 
        : null 
       } 
      ) 
     }) 
     return (
      <tbody> 
       {rows} 
      </tbody> 
     ) 
    }, 

    onClick: function(){ 
     this.setState({childVisible: !this.setstate.childVisible}) 
    } 
}); 

我打電話另一個組件CreateRows並將其發送一些數據:

render: function(){ 
     return (
      <div> 
       <ChangeRowCount updatePeople = {this.updatePeople}/> 
       <table> 
        <CreateColumns columns={this.state.table_columns} /> 
        <CreateRows people = {this.state.people}/> 
       </table> 
      </div> 
     ) 
    } 

我意識到我的問題是,當我創建變量rows我包括功能onClick()但它不能「看到」它並得到這個錯誤:

Uncaught (in promise) TypeError: Cannot read property 'onClick' of undefined(…)

關於如何包含onClick()函數以顯示/隱藏Child組件的任何想法?

謝謝!

回答

0

您看到此錯誤,因爲您在地圖功能中調用了this.onClick。 你需要在作爲第二個參數

var rows = this.props.people.map(function(row, i){ 
     return (
      <tr key={i} onClick={this.onClick}>  
       <td>{row['id']}</td> 
      </tr> 
      { 
       this.state.childVisible 
       ? <Child /> 
       : null 
      } 
     ) 
    }, this) 

傳遞this設置地圖功能的情況下看到the documentationthisArg部分的地圖功能

+0

啊確定。另外,我得到了指向{this.state.child.Visible}的'Unexpected token(133:16)(...)'...對此有任何想法? –

+0

我會在4分鐘內將此標記爲正確,當我讓它出現時。 –

+0

無論如何,你只能返回一件事情,所以tr和三元語句需要包裝在一個元素中。我不確定錯誤是從哪裏來的,但如果我不得不猜測它的格式。如果你把它摺疊成一行,它是否仍然給你錯誤 – PhilVarg