首页 > 解决方案 > 使用 redux-form 和 typescript 创建组件的正确形式是什么?

问题描述

我有一个组件(带有 reduxForm 和 Typescript),但需要在组件上使用 'connect'(带有 '<{}, Props>')和 '>' 来装饰组件,因为它会因下一个错误而中断:


.../Project/src/views/MyAccount/MyAccount.tsx
Type error: Property 'handleSubmit' is missing in type '{ onSubmit: (userData: any) => void; userValues: any; avatarImage: RefObject<HTMLImageElement>; uploadAvatar: (files: any) => void; fileInput: RefObject<HTMLInputElement>; }' but required in type 'Readonly<Props & Partial<ConfigProps<{}, Props, string>>>'.  TS2741

我正在尝试很多形式.. 但到目前为止,唯一的解决方案是用'connect'(使用 reduxForm<{},Props>)和 > 我认为有一些更好的形式来创建组件。这是代码!


import React, { Component, Fragment } from 'react';
import CSSModules from 'react-css-modules';
import { InjectedFormProps, reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';

import Heading from '../Heading/Heading';
import Button from '../Button/Button';
import Input from '../Input/Input';

import * as styles from './UserProfile.css';

interface Props {
  userValues: any,
  avatarImage: any,
  uploadAvatar: any,
  fileInput: any,
  handleSubmit: any,
}

const inputField = ({ input, label, type, meta, disabled, field_value }: any) => (
  <div>
    <Input
      {...input}
      labelText={label}
      styleName="input"
      type={type ? type : "text"}
      disabled={disabled ? disabled : false}
      placeholder={field_value ? field_value : ''}
    />
  </div>
)
const isRequired = (value: any) => (
  value ? undefined : 'Field Required'
)

class UserProfile extends Component<Props & InjectedFormProps<{}, Props>> {
  constructor(props: any) {
    super(props);
  }
  public render() {
    // console.log(this.props.userValues)
    return (
      <Fragment>
        <div styleName="right-info">
          <Heading text="Your data" styleName="heading" />
          <form id="UserProfile" onSubmit={this.props.handleSubmit} method="POST" styleName="form">
            <fieldset styleName="fieldset">
              <Field
                name="phone_number"
                label="Phone Number"
                validate={isRequired}
                field_value={this.props.userValues.phone_number}
                component={inputField} />
              <br />
              <Field
                name="company"
                label="Company"
                validate={isRequired}
                field_value={this.props.userValues.company}
                component={inputField} />
            </fieldset>
          </form>
        </div>
        <div styleName="cta-wrapper">
          <Button
            onClick={this.props.handleSubmit}
            text="SAVE CHANGES"
            filled={true} 
          />
        </div>
      </Fragment>
    )
  }
}

const UserProfileWithCSS = CSSModules(UserProfile, styles, { allowMultiple: true });
export default connect()(reduxForm<{}, Props>({ form: 'UserProfile' })(UserProfileWithCSS));


标签: reactjstypescriptreact-reduxredux-form

解决方案


推荐阅读