2017-09-10 106 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)}