无法从React中的onClick调用函数

时间:2017-09-10 15:08:23

标签: 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。知道我做错了什么以及如何解决它?

1 个答案:

答案 0 :(得分:1)

默认情况下,.map()函数将回调绑定到全局环境对象。因此,您的this.renderAuthority函数也会在构造函数中与this绑定。

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)}