Typing redux forms v7 with TypeScript and React

后端 未结 5 2060
野性不改
野性不改 2020-12-29 15:29

I\'ve got a plain react-redux-powered form. I wish for there to be a form.container.tsx and a form.component.tsx, where form.container.tsx holds all the connections to redux

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 16:07

    Here's a fully typed example that allows initializing a form using initialValues and passing additional props (as IOwnProps):

    sampleForm.tsx:

    export interface IFormData {
      userId: string;
    }
    
    export interface IOwnProps {
      foo: string;
    }
    
    export interface IDispatchProps {
      onSubmit: (data: IFormData, dispatch: Dispatch, props: IOwnProps) => void;
    }
    
    type AllSampleFormProps = IOwnProps & IDispatchProps & InjectedFormProps;
    
    const SampleForm: React.SFC = (props) => (
      
    foo={props.foo}
    ); export const DecoratedSampleForm = reduxForm({})(SampleForm);

    sampleForm.ts:

    The trick here is to specify proper return type for mapStateToProps, otherwise compiler will be complaining like other authors pointed out.

    function mapStateToProps(state: AppState, props: IOwnProps): ConfigProps {
      return {
        form: "sampleForm", // Form will be handled by Redux Form using this key
        initialValues: {
          userId: state.somethere.userId // Can also be calculated using props
        }
      }
    }
    
    function mapDispatchToProps(dispatch: Dispatch): IDispatchProps {
      return {
        onSubmit: (formData: IFormData, dispatch: Dispatch, props: IOwnProps) => {
          console.log(formData);
          console.log(props);
        }
      }
    }
    
    export default connect>(
      mapStateToProps,
      mapDispatchToProps
    )(DecoratedSampleForm);
    

    Now this form can be mounted like this:

    
    

提交回复
热议问题