我有一个对象。我需要在 <selector> 但 return 另一个变量上将其名称打印为 <option>

I have an object. I need to print its name as <option> on an <selector> but return another variable

我有一个对象:

company: {
  name: 'Google',
  id: '123asd890jio345mcn',
}

我需要打印它的名称作为 material-ui 选择器的选项(自动完成呈现文本字段)

但是当用户点击它时,我需要return它是一个州或其他东西的 ID,所以我以后可以使用它。

return (
    <Autocomplete
      id="company"
      open={open}
      onOpen={() => {
        setOpen(true);
      }}
      onClose={() => {
        setOpen(false);
      }}
      loadingText="Buscando empresas..."
      isOptionEqualToValue={(option, value) => option.id === value.id}
      getOptionLabel={(option) => option.id}
      renderOption={(props, option) => (
        <Box component="li" {...props}>
          {option.name}
        </Box>
      )}
      options={options}
      loading={loading}
      noOptionsText="Nenhuma empresa cadastrada"
      defaultValue={data.company}
      renderInput={(params) => (
        <TextField
          {...register("company")}
          {...params}
          label="Empresa"
          placeholder="Selecione a empresa"
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? (
                  <CircularProgress color="inherit" size={20} />
                ) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />
  );
}

With that configuration, when user clicks on any option it retrieves it's ID as value, but I want to show the name on the input instead.

我已经尝试了很多。但是我可以从此自动完成中检索到的唯一参数是它的当前值,即 ID 或名称。我无法显示姓名和检索 ID。

可能吗?

您尝试过使用 onChange 吗?您可以从 onChange 第二个参数 value 获取整个对象。我在这里做了一个简化版本:https://codesandbox.io/s/react-repl-forked-nqv8pw?file=/src/index.js:464-504

<Autocomplete
  // your other props
  getOptionLabel={(option) => option.name}
  onChange={(_, value) => console.log(value)}
  // your other props
/>