2016-03-21 2 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> 
); 
} 

Я хочу, чтобы иметь возможность работать с myVar (на основе стоимости <select> входных), и anotherVar в моей handleSelect функции. Как правильно передать значение элемента <select> в этом случае?

ответ

0

Мое решение было понять, что event все еще передается при использовании bind передать переменную в функцию как handleSelect.

я мог бы использовать onChange={this.handleChange.bind(this, anotherVar} в моем <select> элемента и доступ к переменным, как это:

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> 
    ); 
} 
Смежные вопросы