【发布时间】:2020-06-17 11:55:07
【问题描述】:
当用户从我的文件输入中选择新图像时,我试图在我的 src 中显示图像。
我开始在我的 React 应用程序中将我的 img src 设置为 src={"http://localhost:3000/" + this.props.file} 工作正常,其中 this.props.file 类似于 public/1583271311520-audioplayer.jpg ,我从我的数据库中的数据获取请求
this.state = {
image: {},
};
componentDidMount() {
const { match: { params} } = this.props;
let album = this.state.album;
fetch(`http://localhost:3000/albums/${params.albumId}`)
.then((response) =>
response.json())
.then((data) => {
this.setState({ image: data[0].path });
}).catch((error) => {
console.log("Error " + error)
})
}
数据如下所示:
this.props.files 的父母是这个file={this.state.image}
我的问题是当用户使用文件输入选择 event.target.files[0] 到我的 img src 时,我如何才能在选择新图像时显示图像。
我首先将图像设置为
<img src={" http://localhost:3000/" + this.props.file} />
虽然我试图在此处设置 onChange:
<input type="file" onChange={this.props.onChange} />
onChange(event) {
console.log(event.target.files[0])
this.setState({
image: URL.createObjectURL(event.target.files[0]),
});
}
但我认为我的问题是,在设置我的图像 onChange 时,我设置的图像不是来自 localhost:3000,所以它不能正确渲染。那么,当用户选择图像时,如何使用 onChange 或其他方式将图像添加到我的 img src 中。
【问题讨论】:
标签: reactjs