react下拉框获取值

Posted on 2019-07-10 11:42  猫头唔食鱼  阅读(8763)  评论(0编辑  收藏  举报

1.遍历选项,option里的value去掉,把value写到select里

2.onChange方法写到select标签里

import React, { Component } from 'react'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      cities:["北京","上海","广州"],   //选项
      city:"广州"   // 默认选项
     }
  }
  render() { 
    return (
      <div>
        {/* value放在select里 select框也要onChcange*/}
        <select value={this.state.city} onChange={(e)=>this.getValue(e)}>
          {
            // 遍历option
            this.state.cities.map((ele,index)=>{
              return(
                <option key={index}>{ele}</option>
              )
            })
          }
        </select>
      </div>
     );
  }
  getValue=(event)=>{
    //获取被选中的值
    console.log(event.target.value);
    this.setState({
      //默认值改变
      city:event.target.value
    })

  }
}
 
export default App;