2016-03-21 48 views
0

這裏是我的<select>組件:如何通過React <select>組件傳遞多個參數?

handleSelect: function(myVar, anotherVar) { 
    // Do I need to somehow use event.preventDefault(); here? 
    // I want to be able to do something with myVar and anotherVar here... 
    // ...but it seems I cannot access the event and the value of anotherVar 
    // at the same time...at least not this way. 
}, 
render: function() { 
    let myVar = "Yes", 
     anotherVar = "Another value", 
     id = 1; 
    return (
    <select defaultValue={myvar} onChange={this.handleChange.bind(this, anotherVar}> 
     <option value="Yes">Yes</option> 
     <option value="No">No</option> 
    </select> 
); 
} 

我希望能夠在我的handleSelect功能與myVar(基於<select>輸入的值)anotherVar工作。在這種情況下,我該如何正確傳遞<select>元素的值?

回答

0

我的解決辦法是要認識到,event仍然通過當您使用bind一個變量傳遞給一個函數像handleSelect

我可以在我的<select>元素使用onChange={this.handleChange.bind(this, anotherVar}和訪問這樣的變量:

handleSelect: function(anotherVar, event) { 
    event.preventDefault(); 
    let myVar = event.target.value; 
    ...rest of my code using myVar and anotherVar... 
}, 
0

瓦爾都應該是國家,並在構造函數中定義:

class FooComponent extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { myvar: 'foo', anotherVar : '' }; 
} 
handleSelect(event){ 
    this.setState({anotherVar: event.target.value}, console.log('My var ' + this.state.myvar)); 
} 
render(){ 
    return(
     <div> 
      <select id="blabla" onChange={this.handleSelect.bind(this)} value={this.state.myvar}> 
       <option value="select">Select</option> 
       <option value="Java">Java</option> 
       <option value="Ruby">Ruby</option> 
      </select> 
      <p></p> 
      <p>{this.state.anotherVar}</p> 
     </div> 
    ); 
}