从所需输入添加的 Ant 设计反应 TypeScript 不起作用

Ant design react TypeScript added from input required doesn't work

我试图将 react Typescript 项目添加到 Antdeisgn forms 输入要求它不起作用。

此处出错 当我添加这个 const { getFieldDecorator } = this.props.form;

我遇到了以下错误

  TS2339: Property 'form' does not exist on type 'Readonly<Props> & Readonly<{ children?: ReactNode; }>'.

谁知道如何正确解决这个问题 stack blitz here

我的代码在这里

    import React from 'react';
    import ReactDOM from 'react-dom';
    import 'antd/dist/antd.css';
    import { Form, Input, Button, Checkbox } from 'antd';

    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 8 },
    };
    const formTailLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 8, offset: 4 },
    };
  export  class DynamicRule extends React.Component<any> {


      check = () => {
        this.props.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      };



      render() {
        const { getFieldDecorator } = this.props.form;
        return (
          <div>
            <Form.Item  label="Name">
              {getFieldDecorator('username', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your name',
                  },
                ],
              })(<Input placeholder="Please input your name" />)}
            </Form.Item>


            <Form.Item >
              <Button type="primary" onClick={this.check}>
                Check
              </Button>
            </Form.Item>
          </div>
        );
      }
    }

根据您在下方的评论。我已经采用了您的原始代码并向状态添加了一个具有默认值的构造函数:

// Added constructor and default value for checkNick
  constructor(props) {
    super(props)
    this.state = {
      checkNick: false
    }
  }

我还添加了 handleChange,因为你的代码中有它,但它不起作用:

  // Added handleChange
  handleChange = (e) => {
    this.setState({checkNick: e.target.checked})
  }

这是完整的工作示例:https://stackblitz.com/edit/react-hkzvcx-bbuv6y

import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox } from 'antd';


class DynamicRule extends React.Component {

  // Added constructor and default value for checkNick
  constructor(props) {
    super(props)
    this.state = {
      checkNick: false
    }
  }


  check = () => {
    this.props.form.validateFields(err => {
      if (!err) {
        console.info('success');
      }
    });
  };

  // Added handleChange
  handleChange = (e) => {
    this.setState({checkNick: e.target.checked})
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Form.Item  label="Name">
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: 'Please input your name',
              },
            ],
          })(<Input placeholder="Please input your name" />)}
        </Form.Item>
        <Form.Item label="Nickname">
          {getFieldDecorator('nickname', {
            rules: [
              {
                required: this.state.checkNick,
                message: 'Please input your nickname',
              },
            ],
          })(<Input placeholder="Please input your nickname" />)}
        </Form.Item>
        <Form.Item >
          <Checkbox checked={this.state.checkNick} onChange={this.handleChange}>
            Nickname is required
          </Checkbox>
        </Form.Item>
        <Form.Item >
          <Button type="primary" onClick={this.check}>
            Check
          </Button>
        </Form.Item>
      </div>
    );
  }
}

const WrappedDynamicRule = Form.create({ name: 'dynamic_rule' })(DynamicRule);
ReactDOM.render(<WrappedDynamicRule />, document.getElementById('container'));

对于antd v3,传入FormComponentProps泛型参数可以解决你的问题

import { FormComponentProps } from 'antd/lib/form'

export class DynamicRule extends React.Component<FormComponentProps> {
  // ...
}

通过查看代码和依赖关系,我相信您使用的是 Ant Design 版本 4。在版本 4 中,您可以像这样在 Form.Items 中设置规则:

 //Validators
  function handleTextValidation(rule:any,values:any,callback:any){
    console.log(values)
    const letters = /^[A-Za-z\s]+$/;
    if(!values.match(letters))
      callback("Please enter only letters");
    else
      callback()
  }

<Form.Item
name={['consignee', 'name']}
label="Consignee Name"
rules={[
  {
    required: true,
    message: 'This field is required!'
  },{ 
    message: 'The input should contain only letters',
    validator: handleTextValidation
  }
]}
hasFeedback={true}
  >
  <Input />
  </Form.Item>