How to get selected value of a dropdown menu in ReactJS

后端 未结 9 1834
迷失自我
迷失自我 2020-12-04 10:03

I\'m using react and I want to get the value of the selected option of a dropdown in react but I don\'t know how. Any suggestions? thanks! My dropdown is just a select like:

相关标签:
9条回答
  • 2020-12-04 10:50

    You can handle it all within the same function as following

    <select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>
    
      <option value="5">5 dollars</option>
      <option value="10">10 dollars</option>
                                             
    </select>

    as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

    0 讨论(0)
  • 2020-12-04 10:55

    Using React Functional Components:

    const [option,setOption] = useState()
    
    function handleChange(event){
        setOption(event.target.value)
    }
    
    <select name='option' onChange={handleChange}>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
    
    0 讨论(0)
  • 2020-12-04 10:57

    Implement your Dropdown as

    <select id = "dropdown" ref = {(input)=> this.menu = input}>
        <option value="N/A">N/A</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>
    

    Now, to obtain the selected option value of the dropdown menu just use:

    let res = this.menu.value;
    
    0 讨论(0)
提交回复
热议问题