我试图使用一个控制的用几个选项来反应MUI Select
元素,但是初始值必须是空的(no初始值-空选择)。这听起来是很常见的行为。默认情况下,我不希望选择其中一个选项。
根据我所读到的,如果该值是字符串,您应该使用''
,而不是将其定义为默认值。但是,在我的示例中,选项是对象,因此唯一的方法是将其设置为undefined
或null
。
这里是一个例子的链接。第一次呈现警告时请注意:
You have provided an out-of-range value undefined for the select component.
以及在选择下列选项时出现的错误:
A component is changing the uncontrolled value state of Select to be controlled. Elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled Select element for the lifetime of the component. The nature of the state is determined during the first render. It's considered controlled if the value is not undefined.
知道该怎么做吗?
发布于 2022-09-04 05:35:32
如果希望将选项的值保留为对象,则可以这样做。我必须承认它看起来不太好看。
function App() {
const [item, setItem] = React.useState("");
return (
<Select
value={item?.type ? JSON.stringify(item.type) : ""}
displayEmpty
onChange={(event) => {
console.log(`changed: ${JSON.stringify(event.target.value)}`);
setItem({ ...item, type: JSON.parse(event.target.value) });
}}
>
{types?.map((type) => (
<MenuItem value={JSON.stringify(type)} key={type.id}>
{type?.name ? type.name : ""}
</MenuItem>
)) ?? []}
</Select>
);
}
我建议将值保留为每个对象的id属性。这将是一种方法:
function App() {
const [item, setItem] = React.useState('');
return (
<Select
value={item}
displayEmpty
onChange={(e) => {
setItem(e.target.value);
}}
>
{types?.map((type) => (
<MenuItem value={type.id} key={type.id}>{type.name ?? ""}</MenuItem>
)) ?? []}
</Select>
);
}
你不需要renderValue道具。此外,请记住,您应该为每个选项添加一个键。
https://stackoverflow.com/questions/73591522
复制相似问题