将prop传递给redux形式的组件时出现Typescript错误

时间:2018-06-26 05:36:15

标签: reactjs typescript redux-form typescript-typings react-redux-form

尝试使用redux-form导出表单组件时遇到以下问题。我正在使用打字稿2.9.2和Redux格式7.3.0。有人知道如何更改我的输入才能与此一起工作吗?

[ts]
Argument of type 'typeof ForgotPasswordForm' is not assignable to parameter of type 'ComponentType<IForgotPasswordFormProps & InjectedFormProps<Readonly<IForgotPasswordFormFields>, I...'.
  Type 'typeof ForgotPasswordForm' is not assignable to type 'StatelessComponent<IForgotPasswordFormProps & InjectedFormProps<Readonly<IForgotPasswordFormField...'.
    Type 'typeof ForgotPasswordForm' provides no match for the signature '(props: IForgotPasswordFormProps & InjectedFormProps<Readonly<IForgotPasswordFormFields>, IForgotPasswordFormProps> & { children?: ReactNode; }, context?: any): ReactElement<any>'.

所以在这里,我有一个像这样的表单组件,我从该组件中删除了很多代码以使其更具可读性,但使接口保持不变:

class ForgotPasswordForm extends Component<IForgotPasswordFormProps> {
    render() {
        return (
            <form>
                <Row center='xs'>
                        <Field name='username'
                               component={TextField}
                               label='Username'
                               className={styles.loginFormInput}
                               spellCheck={false}
                               onChange={this.clearForgotPasswordError}
                               validate={[required]}
                               autoFocus/>
                </Row>
            </form>
        );
    }
}

type IForgotPasswordFormFields = {
    username: string;
};

interface IForgotPasswordFormProps extends InjectedFormProps {
    sendForgotPasswordEmail: (username: string) => Promise<ForgotPasswordResponse>;
    loading: boolean | null;
    toggleForgotPasswordForm: () => void | null;
}

const reduxForgotPasswordForm = reduxForm<Readonly<IForgotPasswordFormFields>, IForgotPasswordFormProps>({
    form: 'ForgotPasswordForm'
})(ForgotPasswordForm) //<=== Error is showing here;

export default reduxForgotPasswordForm;

该组件在父级中的使用方式如下:

<ForgotPasswordForm toggleForgotPasswordForm={this.toggleForgotPasswordForm}/>

1 个答案:

答案 0 :(得分:0)

对于具有相同类型问题的任何人,这是我想出的解决方案,可用于将类型传递给要传递道具的redux形式的组件。因此,在上述问题中,我更改为reduxForm高阶组件键入,如下所示:

const reduxForgotPasswordForm = reduxForm<Readonly<IForgotPasswordFormData>, IPassedForgotPasswordProps>({
    form: 'ForgotPasswordForm'
})(ForgotPasswordForm);

并具有以下接口:

IForgotPasswordFormData {
    username: string;
}

IPassedForgotPasswordFormProps{
    toggleForgotPasswordForm: () => void;
}

然后关键是在创建类和扩展Component时使用的IForgotPasswordFormProps中,我必须具有以下接口来扩展此类类型的InjectedProps:

class ForgotPasswordForm extends Component<IForgotPasswordFormProps>

IForgotPasswordFormProps为:

interface IForgotPasswordFormProps extends InjectedFormProps<Readonly<IFormData>, IPassedForgotPasswordProps> {
    toggleForgotPasswordForm: () => void | null;
}