簡體   English   中英

我應該如何從react元素中的custom屬性獲取值?

[英]How should i get the value from custom attribute in react element?

下面是我的html樣子.....

<select onclick={this.handleClick}>
    <option key="1" value="aaa" data-plan-id="test"></option>
</select>

以下是我的handleClick事件代碼

console.log(e.target.value);   // this will output aaa

我的問題是如何從“測試”的“數據計划ID”屬性中獲取值?

只需閱讀selectedOptions HTMLCollection並從中selectedOptions第一個選項:

console.log(e.target.selectedOptions[0].getAttribute('data-plan-id'));

在現代瀏覽器(IE11 +,請參閱support )中,您可以使用數據集接口代替getAttribute

console.log(e.target.selectedOptions[0].dataset.planId);

您需要遍歷<select>所有<option> ,並檢查值是否相同。 如果是,請檢查dataset 這將具有plan-id

PS。 JavaScript會將虛線數據屬性轉換為camelCase plan-id -> planId

希望這可以幫助!

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM