javascript - 无法从 React 中的 onClick 调用函数

标签 javascript reactjs react-redux

我在组件中有一个渲染,如下所示:

  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/

相关文章:

javascript - React Redux - 在辅助函数中访问现有商店

javascript - 换行符在 Mac 上表示为 "\r"?

reactjs - react-i18next 并用组件替换占位符键

javascript - Angular 2 缓慢的初始加载

reactjs - 如何将 Styled-Component 主题变量传递给组件?

javascript - 登录 React-Redux 后无法重定向

reactjs - mapStateToProps 必须返回一个对象。相反收到了Map{}?

redux - React-Redux mapDispatchToProps 未收到 mapStateToProps

javascript - HTML5 Datalist auto suggest 显示以搜索关键字开头的列表

javascript - <tr> onClick 不工作