如何在反应中获取选择字段的值? [英] how to get value of select field in react?

查看:75
本文介绍了如何在反应中获取选择字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有材质 UI 的 react-hook-form.单击按钮时,我想获取我的 autocomplete select 框值.目前它以 label 作为 value 我需要 year 应该是一个值

这是我的代码

/>

解决方案

相关API文档

添加:
由于问题类似于下面的内容

<块引用>

当我选择 { title: "The Godfather", year: 1972 } 时,值应该是 1972.当前点击按钮显示 The Godfather 为什么?

我猜上面的答案是在处理这种需求.

如果您只是想要控制台的值,只需从您的数据中找到它,因为不应重复选择选项.

 const onSubmit = data =>{const temp = top100Films.find(x => x.title === data.resolutionCode);常量值 = 温度?temp.year.toString() : "";控制台日志(值);};

I am using react-hook-form with material UI.On button click I want to get my autocomplete select box value. currently it is taking label as a value I need year should be a value

here is my code

https://codesandbox.io/s/react-hook-form-get-started-nt4kh

when I select { title: "The Godfather", year: 1972 }, the value should be 1972. currently on button click is shows The Godfather why ?

<Autocomplete
        options={top100Films}
        getOptionLabel={option => option.title}
        renderInput={params => (
          <TextField
            {...params}
            inputRef={register}
            label={"Resolution Code"}
            variant="outlined"
            name={"resolutionCode"}
            fullWidth
          />
        )}

/>

解决方案

You can find the related API document here

// From
getOptionLabel={option => option.title}
// To
getOptionLabel={option => option.year.toString()}

Update:
option displayed and value selected using different attributes

renderOption={params => (
  <Typography gutterBottom variant="subtitle1" component="h2">
    {params.title}
  </Typography>
)}
getOptionLabel={option => option.year.toString()}

getOptionLabel

Used to determine the string value for a given option. It's used to fill the input (and the list box options if renderOption is not provided).

renderOption

function(option: T, state: object) => ReactNode option: The option to render. state: The state of the component.

Addition:
Since the question is like something below

when I select { title: "The Godfather", year: 1972 }, the value should be 1972. currently on button click is shows The Godfather why ?

I guess the above answer is handling that demand.

If you simply want the value for your console, just find it from your data since the select option should not be duplicated.

  const onSubmit = data => {
    const temp = top100Films.find(x => x.title === data.resolutionCode);
    const value = temp ? temp.year.toString() : "";
    console.log(value);
  };

这篇关于如何在反应中获取选择字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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