Miz*_*lul 1 html javascript ecmascript-6 reactjs
我想从选项中获取数据属性使用react但由于某种原因我无法使用并且我得到null.
<select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}>
<option value="" data-industry="industry1">Select Industry</option>
<option value="" data-industry="industry2">Select Industry 2</option>
</select>
onIndustryChangeOption(event, index, value) {
console.log(event.target.getAttribute('data-industry'));
this.props.setRootState({selectedIndustry: event.target.value});
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,我相信应该有其他方法来做到这一点!
event.target是select,而不是option.你需要得到option:
onIndustryChangeOption(event, index, value) {
const {target} = event;
const option = target.options[target.selectedIndex];
if (option) {
console.log(option.getAttribute('data-industry'));
//this.props.setRootState({selectedIndustry: event.target.value});
}
}
Run Code Online (Sandbox Code Playgroud)
实例:
class Example extends React.Component {
render() {
return <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}>
<option value="" data-industry="industry1">Select Industry</option>
<option value="" data-industry="industry2">Select Industry 2</option>
</select>;
}
onIndustryChangeOption(event, index, value) {
const {target} = event;
const option = target.options[target.selectedIndex];
if (option) {
console.log(option.getAttribute('data-industry'));
//this.props.setRootState({selectedIndustry: event.target.value});
}
}
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);Run Code Online (Sandbox Code Playgroud)
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>Run Code Online (Sandbox Code Playgroud)
也就是说,在给定的例子中,不清楚为什么你不会使用它value.:-)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |