如何在打字稿中使用antd.Form.create?

时间:2017-07-04 06:17:57

标签: forms typescript antd

我有一个由Form.create()创建的登录表单,但是我无法从父组件向此表单传递任何道具,编译器总是会通知错误,如

error TS2339: Property 'loading' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Compone
nt<{}, ComponentState>> & Readonly<{ childr...'.

LoginForm.tsx

import * as React from 'react';
import { Form } from 'antd';
import { WrappedFormUtils } from 'antd/lib/form/Form';

interface Props {
    form: WrappedFormUtils;
    loading: boolean;
    username?: string;
}

class LoginForm extends React.Component<Props, {}> {
    render() {
        const { loading } = this.props;
        return (<div>form {loading ? 'true' : 'false'}</div>);
     }
}

export default Form.create()(LoginForm);

LoginPage.tsx

import LoginForm from './components/loginForm';

const loginPage: React.SFC<Props> = (props) => {
     return (
         <div>
              <LoginForm loading={true}/>
                         ^ error here!
         </div>
     );
 };

我的antd版本是2.11.2

最后我找到了解决方案

class LoginForm extends React.Component<Props & {form:     WrappedFormUtils}, State> {
  render() {
    const { loading } = this.props;
    return (<div>form {loading ? 'true' : 'false'}</div>);
  }
}

export default Form.create<Props>()(LoginForm);

2 个答案:

答案 0 :(得分:29)

  1. 导入FormComponentProps

    import {FormComponentProps} from 'antd/lib/form/Form';
    
  2. 然后有你的组件

    interface YourProps {
        test: string;
    }        
    
    class YourComponent extends React.Component<YourProps & FormComponentProps> {
        constructor(props: YourProps & FormComponentProps) {
            super(props);
            ...
        }
    }
    
  3. 然后使用Form.create()

    导出类
    export default Form.create<YourProps>()(YourComponent);
    

    Form.create上的泛型参数将结果转换为带有YourProps的React ComponentClass - 没有FormComponentProps,因为这些是通过Form.create包装器组件注入的。

答案 1 :(得分:3)

antd文档中我提供了一种更好的方法

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

interface UserFormProps extends FormComponentProps {
  age: number;
  name: string;
}

class UserForm extends React.Component<UserFormProps, any> {
  // ...
}

const App = Form.create<UserFormProps>({
  // ...
})(UserForm);