1

我正在尝试使用自动完成 ,但我需要使值仅存储特定属性而不是完整对象。

例如,这种情况是属性Value,但它可以是任何情况。

const options = [
  { Value: 1, label: "Option 1", anyOtherProp: 123 },
  { Value: 2, label: "Option 2", anyOtherProp: 456 },
  { Value: 3, label: "Option 3", anyOtherProp: 789 }
];

export default function App() {
  const [value, setValue] = useState(null);

  const valueKey = "Value"; // this should be any key

  const handleChange = (e, value) => {
    // what to do here?
    setValue(value[valueKey]);
  };    

  return (
    <div className="App">
      <Autocomplete
        options={options}
        onChange={handleChange}
        value={value}
        getOptionLabel={option => option.label}
        renderInput={props => <TextField {...props} fullWidth />}
      />
    </div>
  );
}

当我这样做时,输入为空且不显示任何内容。

我需要该值只是对象的一个​​属性,而不是完整选项的对象。

这是一个显示问题的代码框。

4

1 回答 1

0

Check for value and call the setValue. also replace value props on CustomAutocomplete to defaultValue, all will work fine. Check the fiddle Fiddle Link

export default function App() {
  const [value, setValue] = useState(null);

  const valueKey = "Value"; // this should be any key

  const handleChange = (e, value) => {
    // what to do here?
    if(value) setValue(value[valueKey]);
  };

  return (
    <div className="App">
      <CustomAutocomplete
        onChange={handleChange}
        defaultValue={value}
        options={options}
      />
    </div>
  );
}
于 2020-01-21T12:06:49.320 回答