'Ant Design]When managing the check box value in Form.item as useState, the value cannot be recognized

When managing the checkbox value as useState in Form.item, the value is not recognized. As you can see from the source below, clicking on the check box in the item does not change the value, but clicking on the area displays modal, and then checks if you agree. Therefore, the value is managed as useState, but the two issues cannot be resolved.

  1. When I submit on the form, it is not checked, so I get an error message requesting input, but I want the error to disappear as soon as I check it, but I can't solve it unless I press submit again.
  2. If you enter all items and press submit, the value will be displayed as undefined. What's wrong with you...?
export default function Agreement({ name = '', title = '', content = '' }: agreement) {
  const [visible, setVisible] = useState(false)
  const [check, setCheck] = useState(false)
  const [valid, setValid] = useState(true)
  const onCancel = () => setVisible(false)
  const onDisagree = () => {
    setCheck(false)
    setVisible(false)
  }
  const onAgree = () => {
    setValid(true)
    setCheck(true)
    setVisible(false)
  }
  const onClick = (e) => {
    e.preventDefault()
    setVisible(true)
  }
  const validateValue = () => {
    if (!check) {
      setValid(false)
      return Promise.reject(new Error('required check'))
    }
    setValid(true)
    return Promise.resolve(check)
  }

  return (
    <>
      <Item
        name={name}
        htmlFor={name}
        style={{ marginBottom: 0 }}
        rules={[{ type: 'boolean', validator: validateValue }]}
        hasFeedback>
        <div
          onClick={onClick} // open modal
          className={valid ? '' : 'is-error'} // red border
          style={{ padding: '8px', border: '1px solid #D9D9D9', width: '100%' }}
          aria-hidden>
          <Checkbox
            onClick={(e) => {
              e.preventDefault()
            }}
            checked={check}></Checkbox>
          {t(title)}
        </div>
      </Item>
      {visible && (
        <ModalAgreementDetail
          title={title}
          content={content}
          onCancel={onCancel}
          onDisagree={onDisagree}
          onAgree={onAgree}></ModalAgreementDetail>
      )}
    </>
  )
}




Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source