我正在使用ReactJS为我的网站设计一个个人资料页面.

import React, {Component} from 'react';
import { connect } from 'react-redux';
import { AccountAction } from '../../actions/user/AccountPg1Action';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

class AccountInfo extends Component {
  constructor(props) {
    super(props) 
    this.state = {
      currentStep: 1,
      userAccountData: {
        userid: '',
        useravtar: '',
        attachement_id: '',
   }
  }
 }

handleFileUpload = (event) => {
  this.setState({useravtar: event.currentTarget.files[0]})
};

handleChange = event => {
    const {name, value} = event.target
    this.setState({
      [name]: value
    })    
  }

handleSubmit = event => {
    let that = this;
    const { AccountAction } = that.props;
    event.preventDefault();

    let accountInputs = {
      userid: 49,
      useravtar: that.state.image,
      attachement_id: 478,
}
    that.setState({
      userAccountData: accountInputs,
    })

    AccountAction(accountInputs)
  }
AccountInfoView = () => {
console.log(this.state.useravtar)
    return (
      <section id="account_sec" className="second_form">
      <div className="container">
      <React.Fragment>
        <Formik
          initialValues={‌{
            file: null,
            email: '',
            phone: ''
          }}
          validationSchema={accountInfoSchema}
          render={(values) => {
          return(
        <Form onSubmit={this.handleSubmit}>
        <Step1 
          currentStep={this.state.currentStep} 
          handleChange={this.handleChange}
          file= {this.state.useravtar}
          handleFileUpload={this.handleFileUpload}
          />
          </Form>
        );
      }}
      />
      </React.Fragment>
      )
  }

  render() {    

    return (
      <div>{this.authView()}</div>
    )
  }
}

function Step1(props) {
console.log(props.useravtar)
  if (props.currentStep !== 1) {
    return null
  } 

  return(
    <div className="upload">
        <label htmlFor="profile">
          <div className="imgbox">
            <img src="images/trans_116X116.png" alt="" />
            <img src={props.useravtar} className="absoImg" alt="" />
          </div>
        </label>
<input id="file" name="file" type="file" accept="image/*" onChange={props.handleFileUpload}/>
        <span className="guide_leb">Add your avatar</span>
      </div>
  )
}

当我为事件执行handleChange次操作时.目标文件[0]的响应为未定义.

此外,在handleSubmit中执行console.log(this.state.useravtar)操作时,它会显示一个类似c:/fakepath/imgname.jpg的路径名

附言:我有多种形式,所以我用Step种方式.我使用Redux Reducer来存储数据.

我已经提到了this链接,但我的要求不是这样的.

推荐答案

默认情况下,Formik不支持文件上传,但您可以try 以下方法

<input id="file" name="file" type="file" onChange={(event) => {
  setFieldValue("file", event.currentTarget.files[0]);
}} />

这里"file"代表您用来保存文件的密钥

在提交时,你可以使用

onSubmit={(values) => {
        console.log({ 
              fileName: values.file.name, 
              type: values.file.type,
              size: `${values.file.size} bytes`
            })

如果要将文件设置为组件状态,则可以使用

onChange={(event) => {
  this.setState({"file": event.currentTarget.files[0]})};
}}

根据你的代码,你必须按如下方式处理文件上传

在AccountInfo中添加一个函数来处理文件上传

handleFileUpload = (event) => {
this.setState({WAHTEVETKEYYOUNEED: event.currentTarget.files[0]})};
}

并将相同的函数传递给Step1组件,如下所示

    <Step1 
      currentStep={this.state.currentStep} 
      handleChange={this.handleChange}
      file= {this.state.image}
      handleFileUpload={this.handleFileUpload}
      />

在上传文件的步骤1组件中,将输入更改为

<input id="file" name="file" type="file" accept="image/*" onChange={props.handleFileUpload}/>

如果你需要预览上传的图片,你可以创建一个blob,并将其作为图片的源,如下所示

<img src={URL.createObjectURL(FILE_OBJECT)} /> 

EDIT-1

由于安全问题,URL.createObjectURL方法已被弃用,我们需要将srcObject用于媒体元素,例如,要使用ref来分配srcObject

假设您使用的是类组件,

Constructor

在构造函数中,您可以使用

constructor(props) {
  super(props)
  this.imageElRef = React.createRef(null)
}

HANDLE CHANGE FUNCTION

handleFileUpload = (event) => {
  let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
  this.setState({
    file: reader.result
  });
};
reader.readAsDataURL(file);
}

Element

<img src={this.state.file} /> 

Reactjs相关问答推荐

是否将样式应用于父悬停(框架运动)上的子元素?

TypeError:b不是React.js中的函数错误

如何在与AntD的react 中限制文件上传和显示消息?

useState导致对函数的无休止调用

为什么React UseEffect挂钩在页面重新加载时运行

如何动态地改变<; Select >;React和Tailwind元素?

onClick 事件处理程序未应用于样式组件

.populate() 方法在 mongodb 中不起作用

无法通过 fetch 获取数据到上下文中

从ReactDataGridtry 将数据传递给父组件

如何将 DocuSign 控制台界面嵌入到 React 应用中

无法读取未定义的属性(阅读 'editQuoteModalShown')reactredux

redux 工具包使用中间件构建器函数时,必须返回一个中间件数组

React Native 背景动画反转

单击按钮时如何添加或删除 3d 对象

AWS 全栈应用程序部署教程构建失败

动态添加或删除文本输入字段并将值设置为 React JS 中主要状态的数组

如何在 nextjs 中单击按钮时动态导入和渲染组件?

当从数组中删除数据时,UseEffect 不会重新渲染,仅在添加数据时才会重新渲染

在 redux 状态更改时更新react 按钮禁用状态