React Material UI 自动完成 - 如何将文本名称显示为 select 但将 ID 作为值发送?

React Material UI Autocomplete - how to display text name as select but send ID as a value?

MATERUAL UI 自动完成组件 工作正常,但我想获得 object.id 作为 onSelect 事件值(event.target.value ),而不是 object.name。换句话说,我想将 object.name 显示为 select 项标签,但我想将 object.id 显示为 onSelect 事件值 (event.target.value)。现在,我的 event.target.value 与 select 项目标签 (object.name) 相同。这是一个示例(来自 Material UI 文档):

options对象是这样的:

const options = [
  { id: "01", name: "Peter" },
  { id: "02", name: "Mary },
  { id: "03", name: "John" }
]

并且自动完成与 Material UI 文档中的一样:

<Autocomplete
      id="asynchronous-demo"
      fullWidth
      open={open}
      onOpen={() => {
        setOpen(true)
      }}
      onClose={() => {
        setOpen(false)
      }}
      getOptionLabel={(option) => option.name}
      options={options}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Asynchronous"
          variant="outlined"
          onChange={(event) => {
            if (event.target.value !== '' || event.target.value !== null) {
              onChangeHandle(event.target.value)
            }
          }}
          onSelect={(event) => {
            onSelectHandle(event)
          }}
          InputProps={{
            ...params.InputProps,
            endAdornment: (
              <React.Fragment>
                {loading ? (
                  <CircularProgress color="inherit" size={20} />
                ) : null}
                {params.InputProps.endAdornment}
              </React.Fragment>
            ),
          }}
        />
      )}
    />

使用 onSelect 我总是得到 object.name 作为 event.target.value 但我想 return object.id作为 event.target.value.

有人知道怎么做吗?

您目前正在从 TextField 的 onSelect 中获取值,而不是从 Autocomplete 的 onChange 中获取值。

<Autocomplete
    ...
    onChange={(event, newValue) => {
        onSelectHandle(newValue)
    }}
    renderInput={(params) => (
        <TextField
            {...params}
            label="Asynchronous"
            variant="outlined"
            onChange={(event) => {
                if (event.target.value !== '' || event.target.value !== null) {
                    onChangeHandle(event.target.value)
                }
            }}
            ...
        />
    )}
/>

有关详细信息,请查看可控状态部分 in the Autocomplete documentation