在 ReactJS 中处理 "Selected" 选项

Dealing with "Selected" Option in ReactJS

我有以下代码:

<select id="creditCard" ref="card">
 {this.state.cards.map(function(card){
        return(
          <option value={card.ListId}>{card.FullName}</option>
        )
      }, this)}
    </select>

我正在尝试弄清楚如何从 onClick 函数中获取选定的值,但我尝试的似乎无济于事。有什么我想念的想法吗?

目前我正在尝试 this.refs.card.getDOMNode().value 但它只给我文本而不是所选选项值。

一个选择是在 <select> 上使用 onChange 来获取当前值并用它做任何你需要做的事情:

handleChange: function(e) {
  var selectedValue = e.target.value
  // ...
},

// ...in render()
<select id="creditCard" onChange={this.handleChange}>

您可以使用 refs (documentation) and React.findDOMNode as shown below to access the value as shown here:

var Example = React.createClass({
    render: function() {
        return (
        <div>
           <select ref="peopleList">
            {this.props.people.map(function(person){
                return(<option value={person.id}>{person.name}</option>)
      }, this)}                      
           </select>           
           <button onClick={ this.handleClick }>Selected?</button>
       </div>
    );
  },
  handleClick: function() {
      alert(React.findDOMNode(this.refs.peopleList).value);      
  }
});

var people = [
{
    name: 'john',
    id: 1    
},
{
    name: 'irma',
    id: 2    
},
{
    name: 'rita',
    id: 3   
}
];

React.render(<Example people={ people }/>, document.getElementById('container'));