[英]How should i get the value from custom attribute in react element?
Below is my html looks like..... 下面是我的html样子.....
<select onclick={this.handleClick}>
<option key="1" value="aaa" data-plan-id="test"></option>
</select>
Below is my handleClick event code 以下是我的handleClick事件代码
console.log(e.target.value); // this will output aaa
My question is how can I get the value from "data-plan-id" attribute which is "test"?? 我的问题是如何从“测试”的“数据计划ID”属性中获取值?
Just read selectedOptions
HTMLCollection and take the first option from it: 只需阅读selectedOptions
HTMLCollection并从中selectedOptions
第一个选项:
console.log(e.target.selectedOptions[0].getAttribute('data-plan-id'));
With modern browsers (IE11+, see support ) you can use dataset interface instead of getAttribute
: 在现代浏览器(IE11 +,请参阅support )中,您可以使用数据集接口代替getAttribute
:
console.log(e.target.selectedOptions[0].dataset.planId);
You need to loop through all the <option>
of the <select>
and check if the value are same. 您需要遍历<select>
所有<option>
,并检查值是否相同。 If yes, check for dataset
. 如果是,请检查dataset
。 This will have plan-id
. 这将具有plan-id
。
Ps. PS。 Javascript will convert dashed data attribute to camelCase plan-id -> planId
JavaScript会将虚线数据属性转换为camelCase plan-id -> planId
Hope this helps! 希望这可以帮助!
class App extends React.Component{ constructor(){ super() this.onChange = this.onChange.bind(this) this.state = { component: 'A' } } onChange(e){ [...e.target.childNodes].forEach((el) => { //convert HTML collection to array if(el.value === e.target.value) console.log(el.dataset.planId) }) this.setState({ component: e.target.value }) } render(){ return <div> <select onChange={this.onChange} selected={this.state.component}> <option value="aaa" data-plan-id="a plan">A</option> <option value="bbb" data-plan-id="b plan">B</option> </select> </div> } } ReactDOM.render(<App/>, document.getElementById('app'))
<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> <div id="app"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.