首页 > 解决方案 > 如何让 Material-UI AutoComplete renderOption 为选定的值工作?

问题描述

Material-UI Autocomplete 组件让您可以使用一系列选项并像这样转换选项:

您有一组选项对象:[{option}, {option}.....{option}]

我使用 prop 函数renderOption={option => option.title}将选项列表作为选项的标题,并且我想使用选项的 id 作为传递给表单处理程序的实际值,因此我使用内置函数getOptionLabel={option => `${option.id}`}。这一直有效,直到我选择一个选项。输入中的文本显示的是 id,而不是标题。如何让输入的标签成为选项的标题,并且仍然将 id 作为值传递?

       ```
         <Field
            classes={classes}
            name={field}
            label={titleCase(field)}
            InputLabelProps={{
              classes: {
                root: classes.label,
                shrink: 'shrink'
              }
            }}
            component={renderAutoCompleteDataField}
            renderOption={(option )=> option[fieldProp]}
            getOptionLabel={(option =>  `${option.id}`)}
            options={choices}
          />

renderAutoComplete 函数

export const renderAutoCompleteDataField = ({ options, nonfilter, renderOption, getOptionSelected, getOptionLabel, classes, input, onChange, label, fullWidth, value, defaultValue, ...custom }) => {
  return (
          <Autocomplete
          options={options}
          getOptionLabel={getOptionLabel}
          renderOption= {renderOption}
          getOptionSelected={getOptionSelected}
          onSelect={onChange}
          classes={{ 
            listbox: classes.listbox, 
            input: classes.input, 
            option: classes.option 
          }}
          renderInput={(params) => (
            <TextField
            {...params}
            label={label}
            size="small"
            color="secondary"
            variant="outlined"
            fullWidth={fullWidth}
            InputProps={{
              ...params.InputProps,
              className: classes.listbox,
              input: classes.input

            }}
            InputLabelProps={{ className: classes.label }}
            {...input}
            {...custom}
            />
          )}/>

 )
}

标签: javascriptreactjsreduxmaterial-uiredux-form

解决方案


推荐阅读