2016-04-07 63 views
0

我有一个生成的选择,我期待从选定的选项中获得值+自定义属性,到目前为止,我只有它获得的价值。reactjs得到选择的选项自定义属性

var ServiceProviderList = React.createClass({ 
     getInitialState: function(){ 
     return { 
      service_provider_list: this.props.service_provider_list, 
      quickbooks_vendor_id: '', 
      currency: '' 
     }; 
     }, 
     handleChange: function(e){ 
     this.props.onUpdate(e); 
     }, 
     render: function(){ 
     var serviceProviderNodes = this.props.service_provider_list.map(function(item, index){ 
      return(
      <option key = {item.service_provider_id} value={item.quickbooks_vendor_id} data-currency={item.currency}>{item.company_name}</option> 
     ); 
     }, this); 
     return(
      <select value={this.props.quickbooks_vendor_id} data-currency={this.state.currency} id="quickbooks_vendor_id" name="quickbooks_vendor_id" required="required" onChange={this.handleChange}> 
      <option value=""></option> 
      {serviceProviderNodes} 
      </select> 
     ); 
     } 
    }); 

父级:

... 
handleInput: function(e){ 
    this.state.invoice[e.target.id] = e.target.value; 
    this.props.onInvoiceInput(e.target.id, e.target.value); 
}, 

... 
render: function(){ 
... 
<div className="formRow"> 
    <label>Service Provider: </label><br /><ServiceProviderList id="quickbooks_vendor_id" service_provider_list={this.state.service_provider_list} onUpdate={this.handleInput} quickbooks_vendor_id={this.state.invoice.quickbooks_vendor_id} currency={this.state.invoice.currency}/> 
</div> 

handleInvoiceInput(在根元素):

handleInvoiceInput: function(id, val){ 
    this.state.invoice[id] = val; 
    this.setState({invoice: this.state.invoice}); 
} 

回答

0

可以通过使用访问自定义属性:getAttribute('attributename')

handleInput: function(e){ 
    // e.target.getAttribute('data-currency'); will contain the selected currency. 
    this.state.invoice[e.target.id] = e.target.value; 
    this.props.onInvoiceInput(e.target.id, e.target.value); 
}, 
+0

我试过这个,但我不断收到一个空变量,我在代码中的其他地方做错了什么? – Mankind1023

+0

当你检查你的DOM时,数据货币是否在渲染

+0

单个选项具有货币值,但不是选择itselt,当我执行console.log(e)时,它会打印整个select元素。 – Mankind1023