如何键入antd形式validateFields的回调参数

时间:2019-07-11 07:47:54

标签: reactjs typescript antd

问题标题说:在Ant Design中使用Form HOC时如何键入form.validateFields回调参数?

// App.tsx
import { FormComponentProps } from 'antd/lib/form';

interface IProps extends FormComponentProps { ... }

class App extends React.Component<IProps> {
  ...
  handleSubmit = () => {
    const { form } = this.props
    // the `err` and `values` has `any` type
    // how can I type them, or at least type values?
    form.validateFields((err, values) => { ... }))
  }
  ...
}

export default Form.create<IProps>()(App);

3 个答案:

答案 0 :(得分:1)

请注意,您也需要输入create()

// App.tsx
interface UserFormProps extends FormComponentProps {}

...
handleSubmit = () => {
  const { form } = this.props
  form.validateFields((err : any, values: any) => { ... }))
}
...
export default Form.create<UserFormProps>()(App);

答案 1 :(得分:1)

好吧,在挖掘Form.d.ts源代码仅几步之后,我找到了答案。

FormComponentPrps接受默认为any的泛型类型,添加泛型可以键入values回调的form.validateFields参数:

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

interface IFields {
  name: string;
  password: string;
}

interface IProps extends FormComponentProps<IFields> { ... }

顺便说一句,err参数似乎总是any类型

答案 2 :(得分:1)

在 Antd v4 中,验证字段是这样完成的:

// antd v4
validateFields().then(values => {
  // Do something with value
});