Подтвердить что ты не робот

Как использовать antd.Form.create в typescript?

У меня есть форма входа, созданная 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);
4b9b3361

Ответ 1

  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 приводит результат к классу React ComponentClass с YourProps - без FormComponentProps, поскольку они внедряются через компонент-оболочку Form.create.

Ответ 2

Я получил лучший подход от 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);