我不会在递归中传输参数props
:
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"));
但是我收到了一个错误:
未捕获的TypeError:无法读取未定义的属性“state”
在递归调用自身class
的行中,我试图传递props
中存储的值this.state
:
<li key={index}><App a={this.state.a} node={node} /></li>
codepen上的代码: https://codepen.io/alex183/pen/ygEJwd
如何最好地传递递归props
?
答案 0 :(得分:1)
因为您正在为地图使用匿名函数,所以'this'不会引用当前的App类。如果你控制它.log它会看到它是未定义的。您可以将其更改为保留“this”上下文的箭头函数:
.map((node, index) => { /* Same as before */ }
或者您可以在输入功能
之前复制该值const a = this.state.a
// Same as before
.map((node, index) => { /* Same as before, but now a={a} */ }
或者您可以将'this'作为第二个参数传递给它,它将为您设置上下文:
.map(function(node, index) { /* Same as before */}, this);