【问题标题】:How can i make mandatory to click one of the toggle buttons in form?如何强制单击表单中的切换按钮之一?
【发布时间】:2020-05-03 11:11:41
【问题描述】:

如何强制单击反应表单中的切换按钮之一?当用户按下提交按钮时,如果切换没有单击其中一个按钮,我想显示一个错误。我在表单中写了 required 但它仍然不起作用。简而言之,我想让点击其中一个切换按钮成为必要。我该怎么做?

我用this component

组件示例

    const FormButtonGroup = ({
                             question,
                             formKey,
                         }) => {

    const dispatch = useDispatch()
    const reduxValue = useSelector(state => state.app.forms.f3[formKey].value)
    const isSaved = useSelector(state => state.app.forms.f3[formKey].saved)

    const [input, setInput] = useState({
        value: reduxValue,
        valid: true,
    })

    const changeSelected = val => {
        setInput({...input, value: val, valid:val})
        dispatch(saveAnswer('f3', formKey, val))
    }

    useEffect(() => {
        setInput({...input, value: reduxValue})
    }, [reduxValue])

    useEffect(() => {
        if (isSaved) {
            dispatch(resetSavedStatus('f3', formKey))
        }
    }, [isSaved])

    return (
        <>

            <Row>
                <Col className='col-10'>
                    {question}
                </Col>
                <Col className='col-2'>
                 <form>
                    <ToggleButtonGroup name={formKey}
                                       type='radio'
                                       onChange={changeSelected}
                                       value={input.value}
                                       vertical={false} toggle>
                        <ToggleButton
                            className='btn-group'
                            key='1'
                            value={'true'}
                        >
                            Yes
                        </ToggleButton>
                        <p></p>
                        <ToggleButton
                            className='btn-group'
                            key='2'
                            value={'false'}
                        >
                            No
                        </ToggleButton>
                    </ToggleButtonGroup>
                </form>
                </Col>
            </Row>
            <div className='row' style={{marginTop: '-2rem'}}>
                <div className='col-2 ml-auto'>
                    <Button className='next-button' type={"submit"}>
                        Complete
                    </Button>
                </div>
            </div>
        </>
    )
}

【问题讨论】:

    标签: javascript node.js reactjs react-hooks


    【解决方案1】:

    为其中一个按钮使用默认值

    【讨论】:

    • 你能再解释一下吗?能举个例子吗?
    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多