ReactAntd(十八) React-表单按钮点击时间倒计时

表单按钮点击

  • 第一点 Form Button 按钮 disabledflag

  • 第二点 失去焦点 handlelostfocus

  • 第三点 验证 validateUserName

function useLogin(props) {
  //按钮能点不能点
  const [disabledflag, setdisableflag] = useState(true)
  const [username, setUsername] = useState('')
  //验证用户名函数
  function validateUserName(rule, value) {
    if (value) {
      if (value !== 'admin') {
        setUsername({
          validateStatus: 'error',
          errorMsg: '用户名必须是admin',
        })
      } else {
        setUsername({
          validateStatus: 'success',
          errorMsg: null,
        })
      }
    } else {
      setUsername({
        validateStatus: 'error',
        errorMsg: '用户名不能为空',
      })
    }
  }

  //失去焦点
  function handlelostfocus() {
    //不能判断error 只能判断success
    if (
      username.validateStatus === 'success' &&
      password.validateStatus === 'success'
    ) {
      setdisableflag(false)
    } else {
      setdisableflag(true)
    }
  }
  return (
    <Form>
      <Form.Item
        name="username"
        rules={[
          {
            validator: async (rule, value) => {
              validateUserName(rule, value)
            },
          },
        ]}
        help={username.errorMsg}
        validateStatus={username.validateStatus}
      >
        <Input
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="Username"
          onBlur={handlelostfocus}
        />
      </Form.Item>

      <Form.Item>
        <Button
          type="primary"
          htmlType="submit"
          className="login-form-button"
          disabled={disabledflag}
        >
          Login
        </Button>
        Or <div>register now!</div>
      </Form.Item>
    </Form>
  )
}

时间倒计时开始

function useTimeless() {
  const [timer, settimer] = useState('Login')
  const onFinish = (values) => {
    console.log('Received values of form: ', values)
    setdisableflag(true)
    let index = 10
    let timerresult = setInterval(() => {
      index--
      settimer(index + 's之后能点击')
      if (index === 0) {
        clearInterval(timerresult)
        index = 10
        setdisableflag(false)
        settimer('Login')
      }
    }, 1000)
  }
  return (
    <Form.Item>
      <Button type="primary" htmlType="submit" className="login-form-button">
        {timer}
      </Button>
      Or <div>register now!</div>
    </Form.Item>
  )
}

文章作者: 雾烟云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 雾烟云 !
  目录