我在组件中有一个渲染,如下所示:
render() {
if (!this.props.authorities) {
return <div>Loading...</div>
}
return (
<div>
<Col xsOffset={0.5} md={2}>
<ButtonGroup Col xsOffset={1} md={4} justified centered>
<DropdownButton title="Authority" id="bg-justified-dropdown">
{this.props.authorities.map(this.renderAuthority)}
</DropdownButton>
</ButtonGroup>
</Col>
</div>
)
}
}
它使用 renderAuthority 函数呈现下拉项列表,如下所示:
renderAuthority(authorityData) {
return (
<MenuItem onClick={this.clickAuthority(authorityData.LocalAuthorityId)} key={authorityData.LocalAuthorityId} eventKey={authorityData.LocalAuthorityId}>{authorityData.Name}</MenuItem>
)
}
其中的 onClick 调用一个名为 clickAuthority 的函数,如下所示:
clickAuthority(data) {
this.props.fetchRatings(data)
}
我的构造函数也如下所示:
constructor(props) {
super(props);
this.clickAuthority = this.clickAuthority.bind(this);
}
但是,我收到以下错误:
Unhandled Rejection (TypeError): Cannot read property 'clickAuthority' of undefined
这引用了 MenuItem onClick。知道我做错了什么以及如何解决它吗?
最佳答案
默认情况下,.map()
函数将回调与全局环境对象绑定(bind)。因此,也将您的 this.renderAuthority
函数与构造函数中的 this
绑定(bind)。
constructor(props) {
super(props);
this.renderAuthority = this.renderAuthority.bind(this);
this.clickAuthority = this.clickAuthority.bind(this);
}
其次,当你写下这些内容时:
onClick={this.clickAuthority(authorityData.LocalAuthorityId)}
您将立即调用该函数并将其返回值传递给 onClick
属性。你必须这样做:
onClick={() => this.clickAuthority(authorityData.LocalAuthorityId)}
关于javascript - 无法从 React 中的 onClick 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46142182/