如何在不改变状态或不重构为基于类的组件的情况下实现此辅助方法?

时间:2019-06-05 18:04:34

标签: reactjs redux react-redux

我正在为调查表单审核添加功能,以便用户可以上传文件,而我担心的是我不希望通过此实现改变状态,我如何重构以下内容以确保这一点?我唯一的选择是将其重构为基于类的组件吗?

// SurveyFormReview shows users their form inputs for review
import _ from "lodash";
import React from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";

import formFields from "./formFields";
import * as actions from "../../actions";

export const onFileChange = event => {
  this.setState({ file: event.target.files });
};

const SurveyFormReview = ({ onCancel, formValues, submitSurvey, history }) => {
  this.state = { file: null };

  const reviewFields = _.map(formFields, ({ name, label }) => {
    return (
      <div key={name}>
        <label>{label}</label>
        <label>{formValues[name]}</label>
      </div>
    );
  });

  return (
    <div>
      <h5>Please confirm your entries</h5>
      {reviewFields}
      <h5>Add an Image</h5>
      <input
        onChange={this.onFileChange.bind(this)}
        type="file"
        accept="image/*"
      />

或者除了将其重构为基于类的组件作为最佳课程外,我别无选择吗?

2 个答案:

答案 0 :(得分:0)

您应该将其重构为一个类。与此类似的东西应该起作用

class SurveyFormReview extends React.Component {
  state = { file: null };

  onFileChange = event => {
    this.setState({ file: event.target.files });
  };

  render() {
    const { onCancel, formValues, submitSurvey, history } = this.props

    const reviewFields = _.map(formFields, ({ name, label }) => {
      return (
        <div key={name}>
          <label>{label}</label>
          <label>{formValues[name]}</label>
        </div>
      );
    });

    return (
      <div>
        <h5>Please confirm your entries</h5>
        {reviewFields}
        <h5>Add an Image</h5>
        <input
          onChange={this.onFileChange}
          type="file"
          accept="image/*"
        />
      </div>
    )
  }
}

仅作为有关优化和内容的注释。

因为这是一种表单,所以建议您使用更好的html元素。

const reviewFields = _.map(formFields, ({ name, label }) => {
  return (
    <fieldset key={name}>
      <span>{label}</span>
      <span>{formValues[name]}</span>
    </fieldset>
  );
});

label元素通常与input元素一起使用。
fieldset元素通常用于数据的表单组
您可以根据需要使用legend元素作为字段集的标题:)

答案 1 :(得分:0)

如果您不想触摸现有代码,则可以创建HOC

const withFile = (Component) => class extends React.Component {
  state = { file: null }
  render() {
    return <Component {...this.props} file={file} onAttach={files => this.setState({ file: files }) />
  }
}

export default withFile(SurveyForm)

现在,您的表单将收到fileonAttach作为道具。