使用 Reactjs 验证验证码

Validate Captcha using Reactjs

我正在开发一个生成随机代码的简单表单,然后检查用户是否输入了正确的代码。

我的问题是我不知道如何匹配用户输入和生成的代码(来自不同的组件)。

希望你理解我。

谢谢。

请检查我的代码

SANDBOX

<Form onSubmit={this.handleSubmit}>
        <FormItem
          validateStatus={captchaError ? "error" : ""}
          help={captchaError || ""}
        >
          {getFieldDecorator("captcha", {
            rules: [{ required: true, message: "Please input code!" }]
          })(
            <Input
              prefix={<Icon type="key" style={{ color: "rgba(0,0,0,.25)" }} />}
              type="text"
              placeholder="captcha"
              addonAfter={<Captcha />}
            />
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            htmlType="submit"
            disabled={hasErrors(getFieldsError())}
          >
            Log in
          </Button>
        </FormItem>
      </Form>

你可以将生成随机数的函数放在验证码组件之外,并将随机数作为 props 传递,例如:

 <Captcha numbers={xxxx} />

antd getFieldsValue 获得 documentation。 另一种通过 onchange 事件获取文本的方法,例如

handleValueChange(e) {
    e.preventDefault()
    console.log("textValue", e.target.value)
}

而你的 input 作为

<Input
   prefix={<Icon type="key" style={{ color: "rgba(0,0,0,.25)" }} />}
   type="text"
   onChange={this.handleValueChange.bind(this)}
   placeholder="captcha"
   addonAfter={<Captcha />}
 />

您需要在 Parent 中获取子值。您可以按照此处的建议使用 Refs to Components 方法:https://github.com/kriasoft/react-starter-kit/issues/909

这里是working code,它会在输入正确的验证码时显示警告。

这会有所帮助! :)