React,Material UI,如何禁用按钮取决于状态2开关按钮

时间:2020-10-10 11:09:03

标签: javascript reactjs material-ui

任务:默认情况下,该按钮处于关闭状态,仅当开关btn更改了其状态(如道具或正确检查)时,如何使其打开。 我认为验证应该在handleChangeState中进行。

const CustomSwitch = ({name, checked, handleChange}) => {
    const [state, setState] = useState(checked);

    const handleChangeState = (event) => {
        setState(!state)
        handleChange(event)
    }

    return (
        <Switch
        required
        checked={state}
        onChange={handleChangeState}
        name={name}
        color="primary"
    />
    )
}

const CustomSaveButton = ({ notifyByEmail,  notifyBySite, notificationType}) => {
    const [isButtonSend, setIsButtonSend] = useState(true);

    const [state, setState] = React.useState({
        email: notifyByEmail,
        site: notifyBySite,
    });

    const handleChange = (event) => {
        setState({ ...state, [event.target.name]: event.target.checked });
        //validate here
    }

    return (
        <>
            <TableCell  align="center">
                <CustomSwitch name="site" handleChange={handleChange} checked={notifyBySite} setIsButtonSend={setIsButtonSend}/>
            </TableCell>
            <TableCell  align="center">
                <CustomSwitch name="email" handleChange={handleChange} checked={notifyByEmail} setIsButtonSend={setIsButtonSend}/>
            </TableCell>
            <TableCell align="center">
                <SaveButton
                    variant="text"
                    disabled={isButtonSend}
                    onClick={save}
   
                />
            </TableCell>

        </>
    )
}

1 个答案:

答案 0 :(得分:0)

您可以将useEffect作为依赖项来使用state

const [state, setState] = React.useState({
  email: notifyByEmail,
  site: notifyBySite
});

React.useEffect(() => {
  setIsButtonSend(!(state.email && state.site));
}, [state]);