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

how to get value of select field in react?

我正在使用 react-hook-form 和 material UI.On 按钮单击我想获得我的 autocomplete select 框值。目前它将 label 作为 value 我需要年份应该是一个值

这是我的代码

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

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

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

/>

您可以找到相关的 API 文档 here

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

更新:
选项显示和值 selected 使用不同的属性

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.

加法:
由于问题如下

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

我想上面的答案是在处理这个需求。

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

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