antd组件库与TypeScript开发总结之问题解决一:Form表单报错

最近常使用ant design pro框架开发项目,画页面时主要用了antd组件库,常遇到些问题,分享一下解决方法。

1、使用getFieldDecorator时报错getFieldDecorator is not defined:

页面报错:ReferenceError: getFieldDecorator is not defined, 控制台报错:OpinionsComp.tsx:80 Uncaught ReferenceError: getFieldDecorator is not defined
解决方法:
(1)引入FormComponentProps :import { FormComponentProps } from 'antd/lib/form';
(2)使用ts定义类型时继承刚才的引入模块,如果没有使用ts,可以忽略该步骤:

interface Props extends FormComponentProps {
...
}
class Comp extends React.Component<Props, State>{...}//泛型继承上面的Props和State

(3)并在render函数中定义:

render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
 }

(4)使用 Form.create() 包裹,不能直接export:
export default Form.create()(组件名)

2、在父组件中使用子组件,子组件名ts验证被划波浪线:

父组件中的调用,Request 是自己封装的子组件:

<Request 
            onCancel={this.cancelFirForm}
 />

(1)定位到子组件内部,在Props中定义父组件中使用的属性:

interface Props extends FormComponentProps {
	onCancel?:Function;//定义类型,不使用ts的伙伴可以忽略
}

(2)在Form.create()的圆括号前面添加<Props>

export default Form.create<Props>()(
  connect()(Comp)
);

3、表单中嵌套子表单时(子表单是封装的子组件),提交时子表单不被验证:

我这里的情形是子表单里的必填项没有被验证到,因为是公司项目,不可截图,这里以文字描述。解决方法:
(1)在父组件中的render函数中写:const {form}=this.props,并在使用子表单组件时,添加一个自定义属性:

<FormAddCom 
            formInstances={form}//form就是上面定义的常量
 />

FormAddCom 是我自定义的子组件。
(2)定位到子组件FormAddCom 内部,在Props中定义父组件中使用的属性formInstances:

interface Props extends FormComponentProps {
	formInstances?:any;//ts定义类型,不使用ts的伙伴可以忽略
}
class FormAddCom extends React.Component<Props>{...}

FormComponentProps是上面第一个报错类型中解释过要引入的表单模块。
(3)在render函数中使用:

render() { 
    const {formInstances:{getFieldDecorator}}=this.props;
    }

这样就可以被验证了。不要忘记第一种报错,再去检查一遍是否缺少代码。

这里我没有显示state,只为了更好的说明上述三个问题,state正常使用。如果有问题可以下方留意,看到会回复。
发布了30 篇原创文章 · 获赞 26 · 访问量 7179

猜你喜欢

转载自blog.csdn.net/aaqingying/article/details/103312285