欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

react ant design自定义组件如何进行表单校验?示例

程序员文章站 2022-06-07 18:19:15
...
  • 自定义组件
import React, { useState } from 'react';
import { Input } from 'antd';

interface PriceInputProps {
  value?: string;
  onChange?: (value: {number: string | undefined; email: string | undefined}) => void;
}

const FormComponent: React.FC<PriceInputProps> = ({value, onChange}) => {


  const [number, setNumber] = useState(value);
  const [email, setEmail] = useState(value);

  const setOnNumberChange = (e) => {
    const newVal = e.target.value
    setNumber(newVal);
    setVals();
  }
  const setOnEmailChange = (e) => {
    const newVal = e.target.value
    setEmail(newVal);
    setVals()
  }
  const setVals = () => {

    if ( onChange ) {
      onChange({
        email, number
      })
    }
  }

  return (
    <>
      <Input
        type="text"
        value={ number }
        onChange={ setOnNumberChange }
        style={ {
          width: 100,
        } }
      />
      <Input
        type="email"
        value={ email }
        onChange={ setOnEmailChange }
        style={ {
          width: 100,
        } }
      />
    </>

  );
};

export default FormComponent

  • 使用
import React  from 'react';
import { Form, Button } from 'antd';

import FormComponent from './formComponent'

const Demo = () => {
  const onFinish = values => {
    console.log('Received values from form: ', values);
  };

  const checkUser = (rule, value) => {
    console.log(value)
    if (value && value.number > 0) { //校验条件自定义
      return Promise.resolve();
    }

    return Promise.reject('请输入准确的用户信息');
  };

  return (
    <Form
      name="customized_form_controls"
      layout="inline"
      onFinish={onFinish}
      initialValues={{
        price: {
          number: 0,
          currency: 'rmb',
        },
      }}
    >

      <Form.Item
        label="标题"
        name="user"
        required
        rules={[{ validator: checkUser }]}
      >
        <FormComponent onChange={(values)=>{
          console.log(values)
        }} />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Demo

效果图
react ant design自定义组件如何进行表单校验?示例

相关标签: React ant.design