簡體   English   中英

無法從React中的onClick調用函數

[英]Unable to call function from onClick in React

我在組件中的渲染如下所示:

  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()函數將回調與全局環境對象綁定。 因此,也將this.renderAuthority函數與this綁定到this.renderAuthority函數中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM