react下拉框獲取值


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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM