首页 > 解决方案 > 选择时如何将图像添加到我的 src

问题描述

当用户从我的文件输入中选择新图像时,我试图在我的 src 中显示图像。我开始在我的 React 应用程序中设置我的 img src,它src={"http://localhost:3000/" + this.props.file}工作正常,我从我的数据库中的数据中获取的数据在哪里?this.props.filepublic/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 中。

标签: reactjs

解决方案


我相信您所说的是用户选择文件(由 生成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(来自上传的文件)时,它不会。


推荐阅读