【问题标题】:How to add only single value from Autocomplete in Material UI?如何在 Material UI 中从自动完成中仅添加单个值?
【发布时间】:2021-07-06 06:14:12
【问题描述】:

我有一个用于添加国家/地区呼叫代码的自动完成组件,但是,相关国家/地区也随之添加。就像单击自动完成下拉列表时一样,会显示所有国家及其特定代码。我的意图是只添加国家代码。请参阅下面的代码以供参考

const [countryData, setCountryData] = useState({});
const [newValue, setNewValue] = useState("");

useEffect(() => {
    setCountryData(codes);
}, []);


<Autocomplete
        id="size-small-standard"
        size="small"
        options={cities}
        onChange={(event, value) => setNewValue(value)}
        autoSelect={true}
        getOptionLabel={(option) =>
          option.country + " " + ` +` + option.calling_code {/* <-- How to display only calling code, but, should show both country name and calling code in drop down  */}
        }
        defaultValue={cities[98]} 
        style={{ width: "100%" }}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            placeholder="Search your country"
            style={{ width: "40%" }}
          />
        )}
      />

最好的解决方案是什么?

以下是 CodeSandbox 链接:https://codesandbox.io/s/material-demo-forked-3ljj2

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您可以将getOptionLabel 更改为仅显示电话前缀,然后使用renderOption 显示带有国家电话前缀的姓名

    return (
      <div className={classes.root}>
        <Autocomplete
          id="size-small-standard"
          size="small"
          options={cities}
          onChange={(event, value) => setNewValue(value)}
          autoSelect={true}
          getOptionLabel={(option) => `+ ${option.calling_code}`}
          renderOption={(option) => (
            <>{`${option.country} + ${option.calling_code}`}</>
          )}
          defaultValue={cities[98]}
          style={{ width: "100%" }}
          renderInput={(params) => (
            <TextField
              {...params}
              variant="standard"
              placeholder="Search your country"
              style={{ width: "40%" }}
            />
          )}
        />
      </div>
    );
    

    现场演示

    更新:

    这是一个更好的示例,您仍然可以在其中搜索国家/地区。

    现场演示

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2021-10-04
      • 2020-05-04
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多