2017-10-21 298 views
0

我将选项值传递给一系列下拉按钮,每个按钮都位于数据数组的子组件中。React引导下拉按钮OnSelect

当在其中一个按钮中选择一个选项时,我将使用onSelect的结果更新父组件中的状态。这是所有工作正常...

//parent component 

    sourceSelected = (event) => { 
    this.setState({ 
     sourceSelected: event 
    }); 

    ... 

    <ButtonToolbar> 
     {MEDIUM.map((medium) => 
     <Medium key={medium.medium_name} medium={medium} onSelectedValue{this.sourceSelected } /> 
    )}; 
    </ButtonToolbar> 

    //child component 
    <DropdownButton title={props.medium.medium_name} id="source-dropdown" onSelect={props.onSelectedValue}> 
    {props.medium.source.map((option, index) => 
    <MenuItem key={index} eventKey={option}> {option} </MenuItem>)} 
    </DropdownButton> 

但是,我还想在状态(mediumSelected = ???)中存储选择该选项的按钮的名称。

反正有没有办法让OnSelect通过这个回来,还是我应该做别的事情?

+0

您使用的终极版的店吗? – Aaqib

+0

不,我不是。在我沿着这条路线走下去之前,我想让它工作 –

+0

您想存储按钮的名称或按钮返回的值吗? – Aaqib

回答

0

好的,我回答这个使用... https://reactjs.org/docs/handling-events.html传递参数给事件处理程序。

的代码是:

//parent component 
    sourceSelected = (medium_name, event) => { 
    this.setState({ 
     sourceSelected: event, 
     mediumSelected: medium_name 
     }); 
    } 
    ... 

    <div className='test'> 
     <ButtonToolbar> 
      {MEDIUM.map((medium) => 
      <Medium key={medium.medium_name} medium={medium} onSelectedValue={this.sourceSelected.bind(this, medium.medium_name) } /> 
     )}; 
     </ButtonToolbar> 
0

您可以利用Javascript事件和this。基本上,传递事件到将要使用的按钮名称的功能,这样

<button name="btn" onClick={e => this.buttonName(e.target.name)}> 

您还需要在您的constructor()

示例代码绑定this

constructor(props) { 
    super(props); 
    // Bind this so you can use it below 
    this.buttonName = this.buttonName.bind(this); 
    } 

    buttonName(e) { 
    console.log(e); 
    } 
    render() { 
    return (
     <div> 
     // Pass the name of the button to the function 
     <button name="btn" onClick={e => this.buttonName(e.target.name)}> 
      Button 
     </button> 
     </div> 
    ); 
    } 

我还在https://codesandbox.io/s/lrwqr303vz上举了一个快速示例。不介意文件名称。

+1

感谢您的支持。但它实际上并不是我需要的按钮点击,因为我使用下拉菜单中的选择功能。我只需要它将按钮名称作为onSelect的一部分从Child中的DropdownButton传递回来 –