首页 > 解决方案 > 材质-uigetOptionLabel - 将空字符串作为值传递

问题描述

我正在使用 material-ui 自动完成功能。我将一些状态数组传递给它的属性选项。我面临的问题是getOptionLabel:

Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string for [""].

我有 2 个组件。孩子一是:

const StateSelect = (props) => {
  const classes = useStyles();
  const handlePick = (e, v) => {
    props.setState(v);
  };
  return (
    <Autocomplete
      className={classes.inputStyle}
      options={states}
      getOptionLabel={(option) => (option ? option.name : "")}
      onChange={handlePick}
      value={props.state}
      renderInput={(params) => (
        <TextField {...params} label="State" variant="outlined" />
      )}
    />
  );
};

在父组件中,我调用了这个子组件:

 <StateSelect
            state={selectedState}
            setState={(state) => setSelectedState(state)}
          />

在父项中,我有控制 StateSelect 值的 React 钩子:

  const [selectedState, setSelectedState] = useState([""]);

因此,当我最初将 selectedState 作为道具传递给 StateSelect 时,它是 [''] 并且我收到此错误消息。如何将空值作为初始值传递而不出现此错误?

我上传了我的代码的简单版本:

https://codesandbox.io/s/smoosh-field-j2o1p?file=/src/inputStates/input.js

标签: javascriptreactjsmaterial-uireact-hooks

解决方案


我得到了同样的错误。而且,以下对我有用。

getOptionLabel={(option) => option.name || ""}

推荐阅读