2017-02-04 40 views
0

我不會傳輸參數props在遞歸:react.js和傳輸參數道具遞歸

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { visible: this.props.root, a:this.props.a }; 
    } 
    toggle(){ this.setState({visible: !this.state.visible}); } 
    render() { 
    let child, classObj; 
    if (this.props.node.child != null) { 
     child = this.props.node.child.map(function(node, index) { return <li key={index}><App a={this.state.a} node={node} /></li> }); 
     classObj = {togglable:true, "togglable-down":this.state.visible, "togglable-up":!this.state.visible }; 
    } 

    let style;  
    if (!this.state.visible) style = {display:"none"}  
    return (
     <div id="tree">{ !this.props.root && 
     <a style={{cursor:"pointer"}} onClick={this.toggle.bind(this)} className={this.props.node.child.length!=0 ? classNames(classObj) : 'togglable' }> 
      {this.props.node.child.length!=0 ? this.props.node.title : <label ><input type="checkbox" /> {this.props.node.title} </label>}    
     </a>} 
     <ul style={style}> {child} </ul>   
     </div> 
    ); 
    } 
} 


const tree = 
    {"_id":"_", "child":[ 
    {"_id":"029", "title":"One title", 
     "child":[ 
     {"_id":"a01", "title":"Two title", "child": []}, 
     {"_id":"8a5", "title":"News", "child": []}, 
     {"_id":"02e", "title":"ACL", 
      "child": [{"_id":"0b0", "title":"Last Title", "child":[]}]} 
     ] 
    } 
    ]}; 


React.render(<App node={tree} root={true} a={true}/>, document.getElementById("app")); 

但我得到一個錯誤:

Uncaught TypeError: Cannot read property 'state' of undefined

在所在行的遞歸調用class本身,我試圖通過存儲在this.state中的值props<li key={index}><App a={this.state.a} node={node} /></li>

codepen上的代碼: https://codepen.io/alex183/pen/ygEJwd

如何最好地進入遞歸props

回答

1

由於您對地圖使用了匿名函數,因此'this'沒有引用當前的App類。如果你使用console.log,你會發現它是未定義的。您可以將其更改爲它保留了「這個」背景下箭頭功能:

.map((node, index) => { /* Same as before */ } 

或者你可以進入該功能前值複製

const a = this.state.a 
// Same as before 
.map((node, index) => { /* Same as before, but now a={a} */ } 

或者你也可以通過「這個」作爲第二個參數來映射,它會爲你設置上下文:

.map(function(node, index) { /* Same as before */}, this); 
+1

謝謝,似乎工作 – alex10