我正在 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);
最佳答案
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
但是,您应该重构代码以避免这种不必要的嵌套。
关于javascript - 存储在 FileList 中的图像未在 React 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543738/