首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MUI -没有初始值的选择抛出警告和错误

MUI -没有初始值的选择抛出警告和错误
EN

Stack Overflow用户
提问于 2022-09-03 10:32:23
回答 1查看 236关注 0票数 0

我试图使用一个控制的用几个选项来反应MUI Select元素,但是初始值必须是空的(no初始值-空选择)。这听起来是很常见的行为。默认情况下,我不希望选择其中一个选项。

根据我所读到的,如果该值是字符串,您应该使用'',而不是将其定义为默认值。但是,在我的示例中,选项是对象,因此唯一的方法是将其设置为undefinednull

这里是一个例子的链接。第一次呈现警告时请注意:

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.

Codesandbox示例

知道该怎么做吗?

EN

回答 1

Stack Overflow用户

发布于 2022-09-04 05:35:32

如果希望将选项的值保留为对象,则可以这样做。我必须承认它看起来不太好看。

代码语言:javascript
运行
复制
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属性。这将是一种方法:

代码语言:javascript
运行
复制
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道具。此外,请记住,您应该为每个选项添加一个键。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73591522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档