我正在尝试将MUI切换组与React Hook Form一起使用,但是提交表单时我无法获取要发布的值。我的切换组组件如下所示:
import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter';
import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft';
import FormatAlignRightIcon from '@material-ui/icons/FormatAlignRight';
import FormatAlignJustifyIcon from '@material-ui/icons/FormatAlignJustify';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import React from 'react';
import {Controller} from "react-hook-form";
export default function TestToggleGroup(props) {
const {control} = props;
const [alignment, setAlignment] = React.useState('left');
const handleAlignment = (event) => {
setAlignment(event[1]);
};
return (
<Controller
name="ToggleTest"
as={
<ToggleButtonGroup
value={alignment}
exclusive
onChange={handleAlignment}
aria-label="text alignment"
>
<ToggleButton value="left" aria-label="left aligned" key="left">
<FormatAlignLeftIcon/>
</ToggleButton>
<ToggleButton value="center" aria-label="centered" key="center">
<FormatAlignCenterIcon/>
</ToggleButton>
<ToggleButton value="right" aria-label="right aligned" key="right">
<FormatAlignRightIcon/>
</ToggleButton>
<ToggleButton value="justify" aria-label="justified" disabled key="justify">
<FormatAlignJustifyIcon/>
</ToggleButton>
</ToggleButtonGroup>
}
value={alignment}
onChange={(e) => {
handleAlignment(e);
}}
valueName={"alignment"}
control={control}
/>
);
}
不确定我做错了什么,但是任何帮助将不胜感激。
答案 0 :(得分:1)
我的解决方法是使用一种效果,使用setValue
手动设置值,然后在getValues()
函数内部使用handleSubmit
来获取值。
const { control, setValue } = props;
//Effect
React.useEffect(() => {
setAlignment('ToggleTest', alignment);
}, [alignment, setAlignment]);