处理 React Hooks 中的选择选项 [英] handling select options in React Hooks

查看:19
本文介绍了处理 React Hooks 中的选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 React Hooks 中的 [useState} 从下拉选择中获取文本值.我只得到值(数字)而不是文本.我已经复制了下面控制选择下拉列表的代码位.我在这里错过了什么?谢谢.

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>

推荐答案

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'));

工作示例

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

这篇关于处理 React Hooks 中的选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆