【问题标题】:how to get 'country_name' selected in select option react js如何在选择选项反应js中选择'country_name'
【发布时间】:2019-09-23 08:02:04
【问题描述】:

我有一个国家列表,我可以得到ID国家列表,如何获得国家名称?

我的状态

this.state = {
   MEMBER_COUNTRY_ID:'',
   MEMBER_COUNTRY_NAME:''
}

这个 html 选择

<Form.Group controlId="countryList">
    <Form.Label><b>Country</b></Form.Label>
    <Form.Control as="select" ref="idCountry" onClick={this.handleSelect}>
     {dataCountry}
    </Form.Control>
</Form.Group>

const dataCountry = this.state.country.map(countryList=> {
   return(
      <option key={countryList.country_id} value={countryList.country_id}>
          {countryList.country_name} //how to get country name?
       </option>
      )
})

这是我的活动

handleSelect(){
  if (this.refs.idCountry) {
      this.setState({
        MEMBER_COUNTRY_ID:this.refs.idCountry.value.
        MEMBER_COUNTRY_NAME:
      })
   }
}

【问题讨论】:

    标签: javascript reactjs select


    【解决方案1】:

    虽然不推荐直接操作状态,但请尝试这种方法。

      <Form.Group controlId="countryList">
            <Form.Label><b>Country</b></Form.Label>
            <Form.Control as="select" ref="idCountry" onClick={(e) => this.handleSelect(e)}>
             {dataCountry}
            </Form.Control>
        </Form.Group>
    
        const dataCountry = this.state.country.map(countryList=> {
           return(
              <option key={countryList.country_id} value={countryList.country_id}>
                  {countryList.country_name} //how to get country name?
               </option>
              )
        })
    
    
        handleSelect = (e)=>{
          if (this.refs.idCountry) {
              this.setState({
                MEMBER_COUNTRY_ID:this.refs.idCountry.value.
                MEMBER_COUNTRY_NAME: this.state.country[e.target.value].country_name
              })
           }
        }
    

    【讨论】:

      【解决方案2】:

      将它与 value={} 中的 id 一起作为对象传递,然后简单地获取它。 Idk 如果这是最佳实践。但我希望它有用。

      <option ... value={{ id: country_id, name: country_name  }}>
      

      就这样吧^

      【讨论】:

        猜你喜欢
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        • 1970-01-01
        • 2021-03-02
        相关资源
        最近更新 更多