我在 React 应用程序中使用 MUI 库中的 Checkbox 组件。我需要根据条件动态选中或取消选中此复选框。
具体情况取决于所查看的商品。本质上,我的应用程序布局由左侧的项目列表组成。单击某个项目后,右侧会显示一个表单,其中包含特定于该项目的预填充值。现在,我尝试在状态变量中使用布尔属性来动态管理复选框的选中状态。
但是,我遇到了错误消息:
MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized. To suppress this warning, opt to use a controlled SwitchBase.
复选框无法动态重新渲染。任何见解将不胜感激。
TIA。
import React, { useState, useEffect } from 'react';
import { Checkbox, FormControlLabel } from '@mui/material';
import { useForm } from "react-hook-form";
function YourComponent({ item }) {
const [checkedItem, setCheckedItem] = useState<boolean>(false);
const { register, handleSubmit, reset } = useForm({ defaultValues});
useEffect(() => {
if (item) {
setCheckedItem(item.booleanProperty);
}
}, [item]);
return (
// other code..
<FormControlLabel
control={<Checkbox defaultChecked={checkedItem}/>}
label="label"
{...register("item")}
/>
// other code..
);
}
export default YourComponent;
我不知道
{...register('item')}
来自哪里,但是当我忽略它时,它在我的情况下工作正常。
我只更改了作为道具给出的项目的类型。
import { useState, useEffect } from 'react';
import { Checkbox, FormControlLabel } from '@mui/material';
interface IItem {
booleanProperty: boolean;
}
function YourComponent(item: IItem) {
const [checkedItem, setCheckedItem] = useState<boolean>(false);
useEffect(() => {
if (item) {
setCheckedItem(item.booleanProperty);
}
}, [item]);
return (
// other code..
<FormControlLabel
control={<Checkbox defaultChecked={checkedItem}/>}
label="label"
// {...register('item')}
/>
// other code..
);
}
export default YourComponent;