简体   繁体   English

如何在反应中获取选择字段的值?

[英]how to get value of select field in react?

I am using react-hook-form with material UI.On button click I want to get my autocomplete select box value.我正在使用带有材质 UI 的react-hook-form 。单击按钮时,我想获取我的autocomplete select框值。 currently it is taking label as a value I need year should be a value目前它正在将label作为一个value我需要年份应该是一个值

here is my code这是我的代码

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

when I select { title: "The Godfather", year: 1972 }, the value should be 1972 .当我选择{ title: "The Godfather", year: 1972 },值应该是1972 currently on button click is shows The Godfather why ?当前按钮点击显示The Godfather为什么?

<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您可以在此处找到相关的 API 文档

// 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,则用于填充列表框选项)。

renderOption渲染选项

function(option: T, state: object) => ReactNode option: The option to render. function(option: T, state: object) => ReactNode option: 渲染选项。 state: The state of the component. state:组件的状态。

编辑 React Hook 表单 - 入门

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 ?当我选择 { title: "The Godfather", year: 1972 } 时,值应该是 1972。当前点击按钮显示 The Godfather 为什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM