【问题标题】:Image stored in FileList not showing in React存储在 FileList 中的图像未在 React 中显示
【发布时间】:2019-10-24 14:39:03
【问题描述】:

我在 React 中处理文件上传,将文件存储在 FileList 中并显示预览。图像似乎存储正确,但没有呈现,alt 文本不断显示。

this.props.file 包含类似这样的内容:file: "blob:http://localhost:3000/1d648245-4447-41a4-b11e-a5a7b385bb9b"

上传组件的代码如下:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import './Upload.css';
import { setFile } from '../../actions/imagefile';

class Upload extends Component {
  static propTypes = {
    history: PropTypes.object,
    setFile: PropTypes.func,
    file: PropTypes.object,
  }

  handleChange = (event) => {
    this.props.setFile({
      file: URL.createObjectURL(event.target.files[0]),
    });
  }

  render() {
    return (
      <div>
        <input type="file" onChange={this.handleChange} />
        <img src={this.props.file} alt="reviewed img" />
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  file: state.imageFile.file,
});

export default connect(mapStateToProps, {
  setFile,
})(Upload);

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux


    【解决方案1】:

    this.props.file 包含类似这样的内容:file: "blob:http://localhost:3000/1d648245-4447-41a4-b11e-a5a7b385bb9b"

    由此我推断this.props.file 是一个具有结构的对象

    {
      file: "blob:http://localhost:3000/1d648245-4447-41a4-b11e-a5a7b385bb9b"
    }
    

    你的propTypes 定义还说props.file 是一个对象

    file: PropTypes.object
    

    所以你应该把你的代码改成

    <img src={this.props.file.file} alt="reviewed img" />
    

    查看链接:

    https://stackblitz.com/edit/react-ubtvsc?file=Upload.js

    但是,您应该重构代码以避免这种不必要的嵌套。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2019-03-15
      • 2019-02-07
      相关资源
      最近更新 更多