我有一个用于添加国家调用代码的自动完成组件,但相关的国家也与它一起添加。就像单击Autocomplete下拉列表时一样,将显示所有国家/地区及其特定代码。我的意图是只添加国家代码。请参阅以下代码以供参考
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
发布于 2021-04-10 17:15:12
您可以将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>
);
实时演示
更新:
这里有一个更好的例子,你仍然可以搜索国家/地区。
实时演示
https://stackoverflow.com/questions/67036793
复制相似问题