gpt4 book ai didi

reactjs - Redux 表单 Typescript 传递自定义 Prop

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:39 25 4
gpt4 key购买 nike

我正在尝试将自定义 Prop 传递到我用 reduxForm 装饰的组件。另外,我对 Typescript 很陌生。

第一个问题是我不能用connect包裹装饰组件:

export default
connect(mapStateToProps)(
reduxForm({
form: 'myform'
})(MyComponent)
)

错误:

Error:(89, 5) TS2345:Argument of type 'DecoratedComponentClass<any, Partial<ConfigProps<any, {}>>>' is not assignable to parameter of type 'ComponentType<{ addressValue: any; isDeliveryAddress: any; customerTypeValue: any; } & DispatchPr...'.
Type 'DecoratedComponentClass<any, Partial<ConfigProps<any, {}>>>' is not assignable to type 'StatelessComponent<{ addressValue: any; isDeliveryAddress: any; customerTypeValue: any; } & Dispa...'.
Type 'DecoratedComponentClass<any, Partial<ConfigProps<any, {}>>>' provides no match for the signature '(props: { addressValue: any; isDeliveryAddress: any; customerTypeValue: any; } & DispatchProp<any> & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

这显然是由错误的类型引起的,但正如我所说,我是 Typescript 的新手,我不确定如何处理这些长错误。目前我不需要将任何 props 传递给 validate 表单函数,但这对以后的任务非常有帮助。

主要问题是我无法将自定义 Prop 传递给装饰组件:

export default reduxForm({
form: 'myform'
})(
connect(mapStateToProps)(MyComponent)
);

表单 Prop :

interface Props extends InjectedFormProps {
onSubmit: () => void;
// some values from the state
loading: boolean; // the custom prop
}

当我尝试这个时:

<MyForm loading onSubmit={this.handleSubmit} />

它抛出另一个错误:

Error:(134, 25) TS2339:Property 'loading' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<FormInstance<any, Partial<ConfigProps<any, {}>>>> ...'.

奇怪的是,我能够传递在 InjectedFormProps 接口(interface)中声明的 Prop ,但我无法传递任何自定义 Prop 。实际上,我可以从 mapStateToProps 函数传递任何 Prop 。也许我只是无法将任何自定义 Prop 传递给带有 reduxForm 的装饰组件。

最佳答案

@types/redux-form 7.0.10 和 redux-form 7.1.2 的工作解决方案:

MyForm.tsx 中定义表单组件:

import * as React from "react";
import { InjectedFormProps, reduxForm } from 'redux-form';
import { connect } from 'react-redux';

interface StateProps {
valueFromState: string;
}

interface Props extends StateProps {
loading: boolean; // the custom prop
}

const MyForm: React.StatelessComponent<Props & InjectedFormProps<{}, Props>> =
({handleSubmit, loading}) => (
<form onSubmit={handleSubmit}>
{loading && (<p>loading...</p>)}
</form>
)

const mapStateToProps = (state: any): StateProps => ({valueFromState: "1"});

export default connect(mapStateToProps)(
reduxForm<{}, Props>({
form: 'myform'
})(MyForm)
);

然后使用它:

import MyForm from './MyForm';
<MyForm onSubmit={() => console.log("submit")} loading />

关于reactjs - Redux 表单 Typescript 传递自定义 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46016711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com