reactjs - 选择时如何将图像添加到我的 src
问题描述
当用户从我的文件输入中选择新图像时,我试图在我的 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.file
我的父母是这个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 中。
解决方案
我相信您所说的是用户选择文件(由 生成URL.createObjectURL()
)时的图像 URL 不起作用,但您已经确定问题是该 URL 被附加到 localhost 域,即<img src={" http://localhost:3000/" + this.props.file} />
.
那么,既然您已经发现了问题,那么您就非常接近于回答您自己的问题了。只需将 URL 的主机部分存储为状态的一部分:
.then((data) => {
this.setState({ image: `http://localhost:3000/${data[0].path}` });
现在,当您使用来自 AJAX 调用的图像时,它将具有完整的域,但当您使用 URL blob(来自上传的文件)时,它不会。
推荐阅读
- c++ - 如果数据竞争无关紧要,unordered_set 线程安全吗?
- jquery - 如何通过单击按钮使用 jQuery 更改 h1 元素内的文本?
- java - 虽然服务活动被放入清单文件,但发生了这个异常
- delphi - 怪轮(Delphi)
- linkedin - LinkedIn API 中的目标受众数
- amazon-web-services - 尝试使用 GCP IAM auth 从 Vault 读取 Secrets 时出现 403 Permission Denied
- angular - 如何在 SPA 的 Authentication Server 上配置客户端 - 带有验证的 REST 架构?
- ruby-on-rails - 如何获取 PDF 内文本的位置/坐标?
- javascript - 如何在内部使用带有回调的 .every
- android - 如何实现谷歌地图网址?