Antd 在 reactjs 中执行表单验证

Antd steps form validation in reactjs

我一直在尝试使用 Antd 逐步创建表单验证,但我在验证部分遇到了困难。我的目标是,如果字段填写不正确,我将无法单击下一步。据我所知,每次单击下一步时我都必须提交表单,但由于我是初学者,我不知道如何使用嵌套组件来完成。配置文件组件嵌套在第三步中。你能帮帮我吗?

const { Step } = Steps;

const steps = [
    {
        title: 'First',
        content: 'First-content',
    },
    {
        title: 'Second',
        content: 'Second-content',
    },
    {
        title: 'third',
        content: <Profile/>,
    },
    {
        title: 'last',
        content: 'Third',
    },
];

const ListingSteps = () => {
    const [current, setCurrent] = useState(0);
    const onChange = current =>{
        setCurrent(current)
    }
 const next = () => {
        setCurrent(current + 1);
    };

    const prev = () => {
        setCurrent(current - 1);
    };

    return (
        <>
            <Steps current={current} onChange={onChange}>
                {steps.map(item => (
                    <Step key={item.title} title={item.title} />
                ))}
            </Steps>
            <div className="steps-content">{steps[current].content}</div>
            <div className="steps-action">
                {current < steps.length - 1 && (
                    <Button type="primary" onClick={() => next()}>
                        Next
                    </Button>
                )}
                {current === steps.length - 1 && (
                    <Button type="primary" onClick={() => message.success('Processing complete!')}>
                        Done
                    </Button>
                )}
                {current > 0 && (
                    <Button style={{ margin: '0 8px' }} onClick={() => prev()} >
                        Previous
                    </Button>
                )}
            </div>
        </>
    );

简介

function Profile() {
    
    return(
        <>
           <Form name="profile" >
                            <Form.Item  name="name" label='Name' rules={[{required:true, message:'Please enter your name' }]}>
                                <Input/>
                            </Form.Item>
                            <Form.Item name="surname" label='Surname' rules={[{required:true, message:'Please enter your name' }]}>
                                <Input/>
                            </Form.Item>
           </Form>
        </>
            

使用form.validateFields()。 单击 Next 按钮时,您可以通过在 validateFields 中传递所有字段 name 来检查当前步骤的所有必填字段。 例如,在您的配置文件组件中,您有两个字段:name & Surname 您可以通过以下方式验证字段:

const onNext = async () => {
        try {
            await form.validateFields(['name', 'surname']);
            setCurrent((prev)=>prev + 1);
        } catch {}
    };

在步骤列表的每个对象中添加一个键,并为该步骤组件传入一个表单字段名称数组。

const steps = [
    {
        title: 'third',
        content: <Profile/>,
        fields: ['name', 'surname']
    },
    ....
];

现在您可以通过从步骤数组中获取每个步骤字段来验证每个步骤组件。

await form.validateFields(steps[current].fields);

检查 FormInstance API: https://ant.design/components/form/#FormInstance