如何获取选择器标签和值并传递给函数

时间:2019-05-23 11:13:00

标签: reactjs react-native

我正在尝试在函数中获取选择器标签和值,因为它们都带有不同的值,并且我需要标签和值的内容才能使用。谢谢您的帮助

  onValueChangeInvoiceType(value: string){
    this.setState({
      invoiceType: value,
    });
  }



  <Picker 
    mode="dropdown" 
    style={{flex: 1}} 
    textStyle={{color: '#696969' }} 
    selectedValue={this.state.invoiceType} 
    onValueChange={this.onValueChangeInvoiceType.bind(this)}>
      <Picker.Item label="Select Option" value="" />
      <Picker.Item label="BOP" value="1" />
      <Picker.Item label="UNASSESSED BUS PROP" value="2" />
      <Picker.Item label="UNASSESSED RES PROP" value="3" />
      <Picker.Item label="FEES" value="4" />
      <Picker.Item label="FINES" value="5" />
      <Picker.Item label="BUILDING PLAN PERMIT" value="6" />
      <Picker.Item label="PERMIT CHARGES" value="7" />
      <Picker.Item label="RENT" value="8" />
      <Picker.Item label="PERMIT" value="9" />
      <Picker.Item label="BUSINESS PROPERTY RATE" value="12" />
      <Picker.Item label="RESIDENCE PROPERTY RATE" value="13" />
  </Picker>
</Item>

我想知道如何将标签内容也传递给onValueChangeInvoiceType函数。

1 个答案:

答案 0 :(得分:0)

这是您的可能解决方案。我使用键从查找对象中获取值/标签组合。我使用key属性进行查找,因为我希望我知道的东西是唯一的。可以是您想要的任何东西。我不熟悉您使用的特定控件,但是这种方法应该可以工作。运行下面的代码片段以查看其功能

const options = [
  {value:'-1', label:'Select...', key:'-1'},
  {value:'1', label:'BOP', key:'A'},
  {value:'2', label:'UNASSESSED BUS PROP', key:'B'},
  {value:'3', label:'UNASSESSED RES PROP', key:'C'},
  {value:'4', label:'FEES', key:'D'},
  {value:'5', label:'FINES', key:'E'},
];


  
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      value: '',
      label: ''
    };
  }

  onChange = (e) => {
    const opt = options.find(op => op.key === e.target.value);
    if(opt){
      this.setState({
        value: opt.value,
        label: opt.label
      })
    }
  }

  render() {
    return (
      <div>
        <select onChange={this.onChange}>
          {options.map(({key,label}) => (
            <option key={key} label={label} value={key} />
          ))}
        </select>
        <p>Value: {this.state.value}</p>
        <p>Label: {this.state.label}</p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>