onClick不适用于选项字段

时间:2018-06-29 12:52:05

标签: javascript reactjs

我有很多国家/地区

[
   "DriverFirst",
   "DriverSecond"
]

以及React组件中的以下代码

Glide.with(mContext)
            .asDrawable()
            .load(mImageUrl)
            .into(mViewHolder.mImageView);

但是这里没有调用我的const countries = [{ name: 'United States', value: 'US', currency: 'USD' }, { name: 'Israle', value: 'IL', currency: 'ILS' }, { name: 'United Kingdom', value: 'UK', currency: 'GBP' }] ... 我想在handleCountryChange(val){ console.log(val) } <select className="form-control input-lg" name="country" placeholder="Country" > { countries.map((val, index) => { return(<option value={val.value} onClick={() => this.handleCountryChange(val)} key={index}>{val.name}</option>) })} </select> 函数内部获取数组的所有字段 ...我该怎么办它是使用javascript还是reactjs?

  

然后onChange会提供事件和目标值,而不是所有字段

3 个答案:

答案 0 :(得分:2)

您应该将处理程序放在select元素上。不在单个option上。

请尝试以下操作。

<select className="form-control input-lg" name="country" placeholder="Country" onChange={(event) => this.handleCountryChange(event)}>
  { countries.map((val, index) => {   
    return(<option value={val.value} key={index}>{val.name}</option>)
  })}
</select> 

答案 1 :(得分:1)

onChange处理程序放在select元素上。

示例

class App extends React.Component {
  state = {
    countries: [
      {
        name: "United States",
        value: "US",
        currency: "USD"
      },
      {
        name: "Israle",
        value: "IL",
        currency: "ILS"
      },
      {
        name: "United Kingdom",
        value: "UK",
        currency: "GBP"
      }
    ]
  };

  handleCountryChange = event => {
    const { value } = event.target;
    const option = this.state.countries.find(
      country => country.value === value
    );
    console.log(option);
  };

  render() {
    const { countries } = this.state;

    return (
      <select
        className="form-control input-lg"
        name="country"
        placeholder="Country"
        onChange={this.handleCountryChange}
      >
        {countries.map((val, index) => {
          return (
            <option value={val.value} key={index}>
              {val.name}
            </option>
          );
        })}
      </select>
    );
  }
}

答案 2 :(得分:0)

我通过将value设置为索引来做到这一点,然后通过数组中的索引值获取元素

handleCountryChange(e){
  this.setState({
    country: countries[e.target.value].value,
    currency: countries[e.target.value].currency
  })
}

<select className="form-control input-lg" name="country" onChange={(e) => this.handleCountryChange(e)}>
  { countries.map((val, index) => {   
    return(<option value={index} key={index}>{val.name}</option>)
  })}
</select>