gpt4 book ai didi

javascript - 使用文件阅读器以 react 状态存储上传的图像

转载 作者:行者123 更新时间:2023-11-30 14:46:38 24 4
gpt4 key购买 nike

为什么reader.onloadend不执行?我想要做的是存储上传图像的 src 并在渲染方法中通过图像数组映射时渲染预览。文件读取器方法需要更改什么才能实际执行?

import React, { Component } from 'react';
import { Button, Input } from 'semantic-ui-react';
class Uploadimage extends Component {
constructor(props) {
super(props);
this.state = {
file: '',
images:[],
};
}

setImages = (e) => {
e.preventDefault();
let { images } = this.state;
const imageFiles = document.getElementById("image");
const filesLength = imageFiles.files.length;
const temp = null;
let reader = new FileReader();

reader.onloadend = () => {
for(var i = 0; i < filesLength; i++) {
let file = e.target.files[i];
temp.push(reader.readAsDataURL(file));
}
this.setState({
images:temp
})
}
}

render() {
let { images } = this.state;
return (
<div>
<form onSubmit={this._handleSubmit}>
<Input id="image" type="file" multiple defaultValue='no file chosen' onChange={this.setImages} />
<Button icon='upload' type="submit" onClick={this._handleSubmit}>Upload Image</Button>
</form>
{images.map((item,index) => <img src={item} />)}
</div>
)
}

}

export default Uploadimage;

最佳答案

我相信您必须将 for 循环逻辑移出 reader.onloadend 方法

直到现在我的印象是使用react时,任何表单字段都可以变成受控组件,但是fileUpload似乎是一个异常(exception)

请参阅下面带有注释的更新代码,抱​​歉,我还没有尝试过:

class Uploadimage extends Component {
constructor(props) {
super(props);
this.state = {
file: '',
images:[],
};

this.fileReader = new FileReader();
}

setImages = (e) => {
e.preventDefault();
let self = this; // unsure if this is needed
self.setState({ images: [] }); // empty out current images array
const imageFiles = e.target.files; // document.getElementById("image"); // You may want to avoid querying the dom yourself, try and rely on react as much as possible
const filesLength = imageFiles.length; // imageFiles.files.length;
// const temp = null;

for(var i = 0; i < filesLength; i++) {
let reader = new FileReader();
let file = imageFiles[i];

reader.onloadend = () => {
self.setState({ images: self.state.images.concat(reader.result); });
}

reader.readAsDataURL(file);
}
}

render() {
let { images } = this.state;
return (
<div>
<form onSubmit={this._handleSubmit}>
<Input id="image" type="file" multiple defaultValue='no file chosen' onChange={this.setImages} />
<Button icon='upload' type="submit" onClick={this._handleSubmit}>Upload Image</Button>
</form>
{images.map((item,index) => <img src={item} />)}
</div>
)
}
}

关于javascript - 使用文件阅读器以 react 状态存储上传的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48815282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com