【问题标题】:How to add an image to my src when selected选择时如何将图像添加到我的 src
【发布时间】: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


    【解决方案1】:

    我相信您所说的是用户选择文件时的图像 URL(由 URL.createObjectURL() 生成)不起作用,但您已经发现问题是该 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(来自上传的文件)时,它不会。

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 1970-01-01
      • 2018-12-13
      • 2021-03-27
      • 1970-01-01
      • 2017-10-19
      • 2018-10-31
      • 1970-01-01
      • 2020-10-07
      相关资源
      最近更新 更多