【问题标题】:How to use antd.Form.create in typescript?如何在打字稿中使用 antd.Form.create?
【发布时间】:2017-12-07 11:17:53
【问题描述】:

我有一个由 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);

【问题讨论】:

    标签: forms typescript antd


    【解决方案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 上的通用参数将结果转换为带有 YourProps 的 React ComponentClass - 没有 FormComponentProps,因为这些是通过 Form.create 包装器组件注入的。

    【讨论】:

    • 有效,但我需要强制添加:constructor(props: YourProps & FormComponentProps) { super(props); } 以实际将道具传递给表单。我建议您使用此信息进行编辑。
    • 我用 FormComponentProps 这样扩展道具:interface YourProps extends FormComponentProps {...},它也适用于我。
    • @SergeiBasharov 是的,在新的 antd 版本中,他们会在 Form.create<...> 上选择你的道具并剥离 FormComponentProps
    【解决方案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);
    

    【讨论】:

    • 你从哪里得到这个?
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 2017-04-15
    • 2020-01-15
    • 1970-01-01
    • 2022-08-04
    • 2020-06-20
    • 2018-12-18
    • 2017-05-07
    相关资源
    最近更新 更多