gpt4 book ai didi

javascript - 我如何存储和访问元素的数据属性,例如 React 中的选择选项

转载 作者:行者123 更新时间:2023-11-30 11:18:57 25 4
gpt4 key购买 nike

我想使用 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});
}

这行不通,我相信应该有其他方法可以做到这一点!

最佳答案

event.targetselect,不是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});
}
}

实例:

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")
);
<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>


也就是说,对于给定的示例,不清楚为什么您不使用 value 代替。 :-)

关于javascript - 我如何存储和访问元素的数据属性,例如 React 中的选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50542640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com