React MUI Select 对象未显示所选值
React MUI Select Object not showing selected value
嘿,我遇到了一个问题,我使用 MUI select 功能为我 select 一个国家。不知道为什么当我 selected 国家时它改变了它的值,但是当在 select 框中时它没有显示任何东西。
const [selectedCountry, setSelectedCountry] = useState({});
const handleChangeCountry = (event) => {
setCountryValue(event.target.value);
};
<FormControl sx={{ m: 1, width: 400 }}>
<InputLabel id="country-label">Country</InputLabel>
<Select
labelId="country-label"
id="country"
value={selectedCountry}
onChange={handleChangeCountry}
MenuProps={MenuProps}
>
{countryList.map((data,index) => (
<MenuItem
key={data.name}
value={data}
>
{data.name}
</MenuItem>
))}
</Select>
<p className="text-black">{selectedCountry.name}</p>
<p className="text-black">{JSON.stringify(selectedCountry, null, 2)}</p>
如您所见,蓝色背景文字下方显示了我 select 编辑的国家/地区,但 select 框中未显示。不知道我哪里做错了。
感谢您帮助推进。
您的 useState
挂钩具有名为 setSelectedCountry
的设置函数,但在 handleChangeCountry
上您尝试使用 setCountryValue
,它不会根据您的 selectedCountry
更新提供的代码,请改成这样:
const [selectedCountry, setSelectedCountry] = useState({});
const handleChangeCountry = (event) => {
setSelectedCountry(event.target.value);
};
另外,selectedCountry
好像应该是一个对象?在这种情况下,请尝试将 Select 值作为 selectedCountry.name
:
传递
<Select
labelId="country-label"
id="country"
value={selectedCountry.name}
onChange={handleChangeCountry}
MenuProps={MenuProps}
>
嘿,我遇到了一个问题,我使用 MUI select 功能为我 select 一个国家。不知道为什么当我 selected 国家时它改变了它的值,但是当在 select 框中时它没有显示任何东西。
const [selectedCountry, setSelectedCountry] = useState({});
const handleChangeCountry = (event) => {
setCountryValue(event.target.value);
};
<FormControl sx={{ m: 1, width: 400 }}>
<InputLabel id="country-label">Country</InputLabel>
<Select
labelId="country-label"
id="country"
value={selectedCountry}
onChange={handleChangeCountry}
MenuProps={MenuProps}
>
{countryList.map((data,index) => (
<MenuItem
key={data.name}
value={data}
>
{data.name}
</MenuItem>
))}
</Select>
<p className="text-black">{selectedCountry.name}</p>
<p className="text-black">{JSON.stringify(selectedCountry, null, 2)}</p>
如您所见,蓝色背景文字下方显示了我 select 编辑的国家/地区,但 select 框中未显示。不知道我哪里做错了。 感谢您帮助推进。
您的 useState
挂钩具有名为 setSelectedCountry
的设置函数,但在 handleChangeCountry
上您尝试使用 setCountryValue
,它不会根据您的 selectedCountry
更新提供的代码,请改成这样:
const [selectedCountry, setSelectedCountry] = useState({});
const handleChangeCountry = (event) => {
setSelectedCountry(event.target.value);
};
另外,selectedCountry
好像应该是一个对象?在这种情况下,请尝试将 Select 值作为 selectedCountry.name
:
<Select
labelId="country-label"
id="country"
value={selectedCountry.name}
onChange={handleChangeCountry}
MenuProps={MenuProps}
>