[英]How to retrieve data from custom attribute on option tag in React
I have a form with a select dropdown with options that are built by looping over an object. 我有一个带有select下拉菜单的表单,该下拉菜单包含通过循环对象构建的选项。 Each option has an associated value
attribute and a custom attribute data
. 每个选项都有一个关联的value
属性和一个自定义属性data
。
I can retrieve the value
just fine but I cannot access the data
attribute. 我可以很好地检索该value
,但无法访问data
属性。 I tried following a JavaScript pattern found here but to no avail. 我尝试遵循此处找到的JavaScript模式,但无济于事。 The value returned is undefined
. 返回的值是undefined
。
Here is the component with the form: 这是具有以下形式的组件:
import React from 'react';
import Option from './Option';
class AddmenuItemForm extends React.Component {
createMenuItemTest(event) {
event.preventDefault();
const menuItem = {
subsectionObjectId: this.subsectionObjectId.value,
orderIndex: this.subsectionObjectId.selectedIndex.data,
}
this.props.addMenuItem(menuItem);
this.menuItemForm.reset();
}
render() {
const { subsections } = this.props;
return (
<div>
<form ref={(input) => this.menuItemForm = input} onSubmit={(e) => this.createMenuItemTest(e)}>
<select
ref={(input) => this.subsectionObjectId = input}
className="input mtm">
{
Object
.keys(subsections)
.map(key => <Option key={key} id={key} details={subsections[key]} />)
}
</select>
<button type="submit">Add New</button>
</form>
</div>
);
}
};
export default AddmenuItemForm;
And here is the Option component: 这是选项组件:
import React from 'react';
class Option extends React.Component {
render() {
const { details } = this.props;
const key = this.props.id;
return (
<option value={key} data={details.numberMenuItems}>
{details.name}
</option>
)
}
}
export default Option;
Rendered HTML looks like this (the <select>
portion): 渲染的HTML如下所示( <select>
部分):
<select>
<option value="KhEncads5F" data="11">Lunch</option>
<option value="rxGeTpqSDF" data="2">Dinner</option>
</select>
Is there a way to retrieve the extra piece of info on the selected <option>
tag? 有没有办法在选定的<option>
标记上检索额外的信息?
Using the ref
you have to your DOM
element you can access the and the selectedOptions
: 使用您对DOM
元素的ref
,您可以访问和和selectedOptions
:
this.subsectionObjectId.selectedOptions[0].getAttribute('data-items')
Check this working example: 检查以下工作示例:
https://jsfiddle.net/1rmftx4z/ https://jsfiddle.net/1rmftx4z/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.