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

问题描述

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

// 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/*"
      />

还是我别无选择,只能将其重构为基于类的组件作为最佳课程?

标签: reactjsreduxreact-redux

解决方案


如果你不想接触现有的代码,你可以创建 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作为道具。


推荐阅读