"this.state" 或方法在 Reactjs 中不可访问
"this.state" or methods are not accessible in Reactjs
我有生成树的示例代码。但是它显示 this.state.action
或 this.onClickNode
未定义的错误,而我已经在构造函数中定义了所有这些错误。
export default class TreeList extends React.Component {
constructor(props) {
super(props)
this.state = {tree: tree, action: null}
this.onClickNode = this.onClickNode.bind(this)
}
onClickNode(node) {
this.setState({active: node})
}
renderNode(node) {
console.log(this.state.action)
return (
<span onClick={this.onClickNode(null, node)}>
{node.module}
</span>
);
}
render() {
return (
<div>
<Tree tree={this.state.tree} renderNode={this.renderNode}/>
</div>
)
}
}
您需要将 this
绑定到您的 renderNode
函数,因为 this
对于 ES6 类 是 not automatically bound。否则,您的函数中将没有适当的上下文。这就是为什么您的 this.state.action
未定义以及无法解析 this.onClickNode
.
的原因
在您的构造函数中,添加
this.renderNode = this.renderNode.bind(this);
此外,如果您想在 onClick 处理程序中使用节点,可以将其切换为
onClickNode(firstParam, node) {
return (event) => {
this.setState({active: node})
}
}
我假设正在发生的事情是 this.renderNode
在调用 render()
时执行,然后执行 this.onClickNode
然后更新 state
。好吧,由于 state
已更新,它将再次调用 render()
。
我有生成树的示例代码。但是它显示 this.state.action
或 this.onClickNode
未定义的错误,而我已经在构造函数中定义了所有这些错误。
export default class TreeList extends React.Component {
constructor(props) {
super(props)
this.state = {tree: tree, action: null}
this.onClickNode = this.onClickNode.bind(this)
}
onClickNode(node) {
this.setState({active: node})
}
renderNode(node) {
console.log(this.state.action)
return (
<span onClick={this.onClickNode(null, node)}>
{node.module}
</span>
);
}
render() {
return (
<div>
<Tree tree={this.state.tree} renderNode={this.renderNode}/>
</div>
)
}
}
您需要将 this
绑定到您的 renderNode
函数,因为 this
对于 ES6 类 是 not automatically bound。否则,您的函数中将没有适当的上下文。这就是为什么您的 this.state.action
未定义以及无法解析 this.onClickNode
.
在您的构造函数中,添加
this.renderNode = this.renderNode.bind(this);
此外,如果您想在 onClick 处理程序中使用节点,可以将其切换为
onClickNode(firstParam, node) {
return (event) => {
this.setState({active: node})
}
}
我假设正在发生的事情是 this.renderNode
在调用 render()
时执行,然后执行 this.onClickNode
然后更新 state
。好吧,由于 state
已更新,它将再次调用 render()
。