【问题标题】:React Material UI Autocomplete - how to display text name as select but send ID as a value?React Material UI Autocomplete - 如何将文本名称显示为选择但将 ID 作为值发送?
【发布时间】:2021-07-11 15:16:24
【问题描述】:

MATERUAL UI 自动完成组件 工作正常,但我想将 object.id 作为 onSelect 事件值 (event.target.value),而不是 object.name。换句话说,我想将object.name 显示为选择项标签,但我想将object.id 显示为onSelect 事件值(event.target.value)。现在,我的 event.target.value 与选择项目标签 (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.nameevent.target.value但我想返回 object.idevent.target.value

有人知道吗?

【问题讨论】:

    标签: javascript reactjs autocomplete material-ui


    【解决方案1】:

    您目前正在从 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

    【讨论】:

    • 伙计,你太棒了!这解决了我的问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 2020-06-10
    • 2021-08-18
    • 2019-11-30
    • 2020-03-29
    • 2021-02-16
    • 2020-11-06
    • 2022-10-12
    相关资源
    最近更新 更多