handling select options in React Hooks

心不动则不痛 提交于 2020-12-30 02:30:23

问题


I am trying to get the text value from a dropdown select using [useState} in React Hooks. I just get the value (number) rather than the text. Ive copied the bits of code below which control the select dropdown. What am i missing here? Thanks.

const [addrtype, setAddrType] = useState('Home')

function handleAddrTypeChange(e) {
    setAddrType(e.target.value);
    console.log(addrtype)
}


                            <select
                                defaultValue={addrtype}
                                onChange={handleAddrTypeChange}
                                className="browser-default custom-select">
                                <option selected value="1">Home</option>
                                <option value="2">Marketing</option>
                                <option value="3">Work</option>
                                <option value="3">Head Office</option>
                            </select>

回答1:


import React, { useState, Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

const App = () => {

  const [addrtype, setAddrtype] = useState(["Work", "Home", "school"])
  const Add = addrtype.map(Add => Add
  )
  const handleAddrTypeChange = (e) => console.log((addrtype[e.target.value]))

  return (
    < select
      onChange={e => handleAddrTypeChange(e)}
      className="browser-default custom-select" >
      {
        Add.map((address, key) => <option value={key}>{address}</option>)
      }
    </select >)


}

render(<App />, document.getElementById('root'));

Working example

https://stackblitz.com/edit/react-select-hook



回答2:


If you want text then access text instead of value. event.target.text. Check the reference here. http://output.jsbin.com/vumune/4/




回答3:


Just change the option value

<option selected value="Home">Home</option>
<option value="Marketing">Marketing</option>
<option value="Work">Work</option>
<option value="Head Office">Head Office</option>


来源:https://stackoverflow.com/questions/58114855/handling-select-options-in-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!