使用TypeScript和React

时间:2017-09-06 14:54:55

标签: javascript reactjs typescript redux redux-form

我有一个简单的反应 - 还原动力形式。我希望有一个form.container.tsx和一个form.component.tsx,其中form.container.tsx包含所有与redux状态的连接减去Field的连接。我试图将我的容器包装在react-redux的连接中,然后将reduxForm包装在其中,看起来像TypeScript, redux-form and connect

(理想)form.container.tsx:

interface DummyFormContainerProps {}

export const DummyFormContainer: React.SFC<DummyFormContainerProps> = props => {
  const submitForm = (formValues: object) => {
    alert(formValues);
  };
  return (
    <DummyForm
      onSubmit={submitForm}
    />
  );
};

const mapStateToProps = (state: State) => ({});
const mapDispatchToProps = (dispatch: object) => {
  return {};
};
const mergeProps = (stateProps: State, dispatchProps: object | null, ownProps: object | void) => 
  Object.assign({}, stateProps, dispatchProps, ownProps);

const formConfiguration = {
  form: 'dummy-form',
  forceUnregisterOnUnmount: true
};

export default connect(mapStateToProps, mapDispatchToProps)(
  reduxForm(formConfiguration)(DummyFormContainer)
);

上面的方法不起作用,但如果我拿出reduxForm()部分,我就会留下一个没有reduxForm集成的工作容器:

(不使用reduxForm)form.container.tsx:

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(
  DummyFormContainer
);

我尝试使用reduxForms和connect进行不同的修改,但目前还没有工作:

(带有类)form.container.tsx:

export class DummyFormContainer extends React.Component<DummyFormContainerProps, void> {
  submitForm = (formValues: object) => {
    alert(formValues);
  }

  render() {
    return (
      <DummyForm
        onSubmit={this.submitForm}
      />
    );
  }
}

const mapStateToProps = (state: State) => ({});
const mapDispatchToProps = (dispatch: object) => {
  return {};
};
const mergeProps = (stateProps: State, dispatchProps: object | null, ownProps: object | void) => 
  Object.assign({}, stateProps, dispatchProps, ownProps);

const formConfiguration = {
  form: 'business-registration',
};

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(
  reduxForm(formConfiguration)(DummyFormContainer) // ERROR
);

错误:

./src/modules/dummy-form/dummy-form.container.tsx
(100,32): error TS2345: Argument of type 'typeof DummyFormContainer' is not assignable to parameter of type 'ComponentType<InjectedFormProps<{}, {}>>'.
  Type 'typeof DummyFormContainer' is not assignable to type 'StatelessComponent<InjectedFormProps<{}, {}>>'.
    Type 'typeof DummyFormContainer' provides no match for the signature '(props: InjectedFormProps<{}, {}> & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

(使用无状态功能组件)form.container.tsx:

export const DummyFormContainer: React.SFC<DummyFormContainerProps> = props => {
  const submitForm = (formValues: object) => {
    alert(formValues);
  };
  return (
    <DummyForm
      onSubmit={submitForm}
    />
  );
};

export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(
  reduxForm(formConfiguration)(DummyFormContainer) // ERROR
);

错误:

./src/modules/dummy-form/dummy-form.container.tsx
(100,3): error TS2345: Argument of type 'DecoratedComponentClass<{}, Partial<ConfigProps<{}, {}>>>' is not assignable to parameter of type 'ComponentType<(State & null & void) | (State & null & object) | (State & object & void) | (State ...'.
  Type 'DecoratedComponentClass<{}, Partial<ConfigProps<{}, {}>>>' is not assignable to type 'StatelessComponent<(State & null & void) | (State & null & object) | (State & object & void) | (S...'.
    Type 'DecoratedComponentClass<{}, Partial<ConfigProps<{}, {}>>>' provides no match for the signature '(props: (State & null & void & { children?: ReactNode; }) | (State & null & object & { children?: ReactNode; }) | (State & object & void & { children?: ReactNode; }) | (State & object & { children?: ReactNode; }), context?: any): ReactElement<any> | null'.

form.component.tsx如下所示:

import * as React from 'react';
import Input from '../../components/input';

interface DummyFormProps {
  onSubmit: (formValues: object) => void
}

export const DummyForm: React.SFC<DummyFormProps> = () => {
  return (
    <div>
      <h1>DummyForm (no state)</h1>
      <form>
        <Input inputType="primary" />
      </form>
    </div>
  );
};

export default DummyForm;

&lt;输入&gt; component是一个常规的React组件。

有谁知道如何正确连接reduxForm和react-redux的connect()?

5 个答案:

答案 0 :(得分:8)

这是一个完全类型化的示例,允许使用initialValues初始化表单并传递其他道具(如IOwnProps):

<强> sampleForm.tsx:

export interface IFormData {
  userId: string;
}

export interface IOwnProps {
  foo: string;
}

export interface IDispatchProps {
  onSubmit: (data: IFormData, dispatch: Dispatch<any>, props: IOwnProps) => void;
}

type AllSampleFormProps = IOwnProps & IDispatchProps & InjectedFormProps<IFormData, IOwnProps>;

const SampleForm: React.SFC<AllSampleFormProps> = (props) => (
  <form onSubmit={props.handleSubmit(props.onSubmit)}>
    <div>foo={props.foo}</div>
    <Field name="userId" component="input" />
    <button type="submit">Submit</button>
  </form>
);

export const DecoratedSampleForm = reduxForm<IFormData, IOwnProps>({})(SampleForm);

<强> sampleForm.ts:

这里的技巧是为mapStateToProps指定正确的返回类型,否则编译器会像其他作者所指出的那样抱怨。

function mapStateToProps(state: AppState, props: IOwnProps): ConfigProps<IFormData, IOwnProps> {
  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<any>): IDispatchProps {
  return {
    onSubmit: (formData: IFormData, dispatch: Dispatch<any>, props: IOwnProps) => {
      console.log(formData);
      console.log(props);
    }
  }
}

export default connect<ConfigProps<IFormData, IOwnProps>>(
  mapStateToProps,
  mapDispatchToProps
)(DecoratedSampleForm);

现在可以像这样安装此表单:

<FormContainer foo="bar"/>

答案 1 :(得分:3)

我发现通过为connect语句提供空TStatePropsTDispatchProps对象,我能够解除错误。

interface SampleFormData {
  username: string;
}

interface SampleFormProps {
  saveData: (data: SampleFormData) => void;
}

type AllSampleFormProps = SampleFormProps & InjectedFormProps<SampleFormData>;

const SampleForm: React.SFC<AllSampleFormProps> = (props) => (
  <form onSubmit={props.handleSubmit(props.saveData)}>
    <Field name="username" component="input" />
  </form>
);

const DecoratedSampleForm = reduxForm<SampleFormData>({ form: "sampleForm" })(SampleForm);

export default connect<{},{}>(
  () => ({}),
  (dispatch) => ({
    saveData: (data: SampleFormData) => dispatch({ type: "SAVE_DATA", data })
  })
)(DecoratedSampleForm);

这样做的一个缺点是它迫使我们盲目地提供连接道具,但我觉得这比写一个覆盖@types声明更优雅。

为了解决这个缺点,我能够通过提供正确的接口与空对象的连接来验证类型;但是,此方法只能临时完成,以检查绑定,因为它无法解决DecoratedComponentClass错误。

export default connect<{}, SampleFormProps, InjectedFormProps<SampleFormData>>(
  () => ({}),
  (dispatch) => ({
    saveData: (data: SampleFormData) => dispatch({ type: "SAVE_DATA", data })
  })
)(DecoratedSampleForm);

答案 2 :(得分:2)

根据https://redux-form.com/7.0.4/examples/initializefromstate/

中的示例,我也遇到了尝试从redux状态初始化我的表单的问题

我最终通过连接更高级别的组件来解决它,例如:

component.tsx:

interface DummyFormComponentProps {} extends InjectedFormProps

const DummyFormComponent: React.SFC<DummyFormComponentProps> = props => {
  return (
    <form onSubmit={props.handleSubmit}>
      // Fields go here
    </form>
  )
}

export const DummyForm = reduxForm({
  form: "dummy-form"
})(DummyFormComponent)

// Trying to connect here also gave errors with DecoratedComponentClass

container.tsx:

interface DummyFormContainerProps {} extends Pick<InjectedFormProps,
  "initialValues"
>

const submitForm = (formValues: object) => {
  alert(formValues);
};

const DummyFormContainer: React.SFC<DummyFormContainerProps> = props => {  
  return (
    <DummyForm 
      initialValues={props.initialValues}
      onSubmit={submitForm}
    />
  )
}

const mapStateToProps = (state: State) => ({
  initialValues: {}
});
const mapDispatchToProps = (dispatch: object) => {
  return {};
};
export default connect(mapStateToProps, mapDispatchToProps)(DummyFormContainer)

答案 3 :(得分:0)

我们最终做的是闭上眼睛,用类型声明文件覆盖默认类型:

终极版-forms.d.ts:

return Integer.valueOf(e1.getSalary()).compareTo(e2.getSalary());

答案 4 :(得分:-3)

我遇到了同样的问题,发现它是由&#34; @ types / react-redux&#34;引起的,删除了这个类型定义文件,一切都按照你期望的方式工作,没有任何其他副作用/类型没有该类型def文件导致的错误。