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
?
謝謝,似乎工作 – alex10