reactjs - 如何在不改变状态或重构为基于类的组件的情况下实现此辅助方法?
问题描述
我正在向调查表单审查添加一项功能,以便用户能够上传文件,我担心我不想通过此实现来改变状态,我如何重构以下内容以确保这一点?我唯一的选择是将其重构为基于类的组件吗?
// 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/*"
/>
还是我别无选择,只能将其重构为基于类的组件作为最佳课程?
解决方案
如果你不想接触现有的代码,你可以创建 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)
现在您的表单将接收file
并onAttach
作为道具。
推荐阅读
- python - 系统位置分析
- flutter - 'package'flutter/src/widgets/framework.dart':断言失败:'child == _child':不正确
- git - 在 Azure DevOps 中,有没有办法快速将拉取请求或变更集应用到不同的 git 存储库?
- c# - 创建新对象如何重置 Windows 窗体上的特定值 - C# Windows 窗体应用程序
- angular - 为什么格式化数据不起作用Angular?
- reactjs - 样式化组件和 ReactJs 的 CSS 中的动态属性
- xcode - 出现在故事板选择下拉列表中的资产
- javascript - 在Javascript中制作水平滚动菜单
- spring - 如何在 CDI bean 中调用服务类接口
- android - 如何从firebase db android中的2个表格中检索数据?