我正在尝试将自定义道具传递给使用reduxForm
修饰的组件。我也是新手稿。
第一个问题是我无法使用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中的新手,我不知道如何处理这些长错误。此时我不需要将任何道具传递给validate
表单函数,但它对将来的任务非常有帮助。
主要问题是我无法将自定义道具传递给装饰组件:
export default reduxForm({
form: 'myform'
})(
connect(mapStateToProps)(MyComponent)
);
表单道具:
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
界面中声明的道具,但我无法传递任何自定义道具。实际上,我可以从mapStateToProps
函数传递任何道具。也许我只是无法使用reduxForm
将任何自定义道具传递给装饰组件。
答案 0 :(得分:9)
gamefile
7.0.10和@types/redux-form
7.1.2:
在redux-form
中定义表单组件:
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)
);
答案 1 :(得分:3)
这里有一个如何定义自定义道具的示例:
import { FormProps, reduxForm } from "redux-form";
interface InitialValuesProps {
name: string;
}
interface CustomFormProps extends FormProps<InitialValuesProps, {}, {}> {
loading: boolean;
}
class CustomForm extends React.Component<CustomFormProps> {
render() {
const loading = this.props.loading
const name = this.props.initialValues.name;
}
}
export default reduxForm({ form: 'myForm' })(CustomForm)