【问题标题】:React, Material UI, how disable button depending on the state 2 switch buttonReact,Material UI,如何根据状态2切换按钮禁用按钮
【发布时间】:2020-10-10 11:09:03
【问题描述】:

任务:默认情况下,按钮是关闭的,如何让它只有在开关 btn 改变了它的状态时才打开,这在 props 中,或者更确切地说是对它的正确检查。 我认为验证应该在 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>

        </>
    )
}

【问题讨论】:

  • 你能分享你的代码吗?

标签: javascript reactjs material-ui


【解决方案1】:

您可以利用 useEffectstate 作为依赖项

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

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

【讨论】:

  • 可能是我拼错了,我只需要在开关按钮的位置发生变化并且它不等于发送到电子邮件和站点字段的道具的状态时打开按钮。
  • 同一个概念;不同的逻辑setIsButtonSend(!(state.email !== notifyByEmail || state.site !== notifyBySite));。在 useEffect 上添加 props 的依赖
  • 哦,非常感谢,我的错误是我在 useEffect 中没有进行此类检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 2018-12-09
  • 2018-09-26
  • 1970-01-01
相关资源
最近更新 更多