我有这个select
JSX:
<select className="form-control" onChange={this.onChange} value={this.props.value}>
{options}
</select>
选项为:
var options = this.props.options.map((option) => {
return (<option key={option.slug} value={option.slug} data-country={option.country} data-continent={option.continent}>{option.value}</option>);
});
但是我无法访问所选选项的所选
data-country
,因为该值是由e.target.value
访问的,并且e.target.dataset
是select
标记的数据集,而不是选项selected的标记: onChange: function(e) {
this.props.onChange(this.props.name, e.target.value, e.target.dataset.continent, e.target.dataset.country);
},
有没有解决的办法?
谢谢
最佳答案
我只会pass一下:
var options = this.props.options.map(option => {
return (
<option key={option.slug} value={option.slug}>
{option.value}
</option>
);
});
...然后使用slug检索数据:
onChange: function(event, index, value) {
var option = this.props.options.find(option => option.slug === value);
this.props.onChange(this.props.name, value, option.continent, option.country);
}
(如果不具备ES6功能,则可以将
.find
替换为forEach
或使用的任何JS。)关于reactjs - react : access data-attribute in <option> tag,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35511600/