javascript - 如何从中获得所需的价值
问题描述
解决方案
可以使用 找到选定的选项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>
推荐阅读
- python - 使用 Materialize 的带有外键的 Django 表单
- vb.net - 检测恢复后何时到达桌面
- python - Telegram Bot 如何使用 sendDocument
- c# - 如何在反序列化期间通过构造函数参数将记录器注入对象
- javascript - 如何在下拉/选择列表中添加复选框选中的项目
- javascript - 为什么我不能从这个结构中获取文章数据?
- java - Marshall/Unmarshall 地图
- awk - 打印第二列的数据
- java - 如何在没有 IndexOutOfRangeException 的情况下正确使用 Fork/Join 框架?
- javascript - 为什么`bind`的返回函数没有`prototype`属性?