2017-09-10 108 views
0

我有一個看起來像這樣的組件中的渲染從的onClick調用函數:無法在陣營

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 

此引用菜單項的onClick。任何想法我做錯了什麼,我怎麼可能解決它?

+0

爲什麼不嘗試{this.props.authorities.map(this.renderAuthority.bind(this)} –

回答

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