首页 > 解决方案 > 如何从中获得所需的价值

问题描述

标签: javascriptreactjsselectoption

解决方案


可以使用 找到选定的选项e.options[e.selectedIndex].value。在反应组件方法中,您需要e.target改用。

这是一个例子。与触发事件handleChange时调用的代码类似。select onChange

class Select extends React.Component {
  
  handleChange(e) {

    // Grab the value from the selected index (option)
    const { value } = e.target.options[e.target.selectedIndex];
    console.log(value);
  }
  
  render() {
    const { options } = this.props;
    return (
      <select onChange={this.handleChange}>
        {options.map((option, i) => {
          return <option key={i} value={option}>{option}</option>
        })}   
      </select>
    )
  }
}

const options = [
  'drink', 'eat', 'dance', 'drive'
];

ReactDOM.render(
  <Select options={options} />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>


推荐阅读