35

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

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

登录表单.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);

登录页面.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);
4

2 回答 2

58
  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 包装器组件注入的。

于 2017-11-09T07:45:38.070 回答
15

我从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);
于 2019-06-11T14:57:10.150 回答