【问题标题】:Creating div with backgroundimage url from state programmatically以编程方式从状态创建带有 backgroundimage url 的 div
【发布时间】:2020-03-08 15:28:29
【问题描述】:

我有一个项目,您可以在表单上上传多张图片,如果您上传一张图片,它需要一个 div 并使用状态将上传图片的 backgroundImage url 添加到基于网格的 div 中。

我的要求是如何动态创建 div 并将网址附加为上传图像状态的 backgroundImage 网址?

示例:<div style={{backgroundImage:url(${this.state.url})}} key={''}>{''}

这很好用,但是我想动态创建 div,例如,如果您添加新项目,它会添加一个带有 backgroundImage url 的新 div,如果有多个项目,它将添加多个具有相应 url 的 div到 backgroundImage 属性。

这是我的图片上传组件:

import React, { Component } from "react";
import "../App.css"
import uploadImages from './uploadImages'
class ImageUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      images: '',
      url: "",
      progress: 0
    };
  }


  handleChange = e => {
    if (e.target.files) {
      const images = e.target.files;
      this.setState(() => ({ images }));
      console.log(images)
    }
  };
  handleUpload = () => {
    if(this.state.images.length === 0) return;        
    uploadImages(this.state.images, "images/", null).then(urls=>{
        this.setState( {url: urls[0]} );
      });
  }


  render() {

    return (

      <div>



         <div className="file-field input-field">
          <div className="btn">
          <input type="file" multiple onChange={this.handleChange} />
        </div>
          <div className="file-path-wrapper">
            <input className="file-path validate" type="text" />
          </div>
    </div>
        <button
          onClick={this.handleUpload}
          className="additem"
        >
          Add Item
    </button>
        <br />
        <br />
        <main>
        <div class="grid">
        <div style={{backgroundImage: `url(${this.state.url})`}} key={''}>{''}
        </div> 


</div>

        </main>
      </div>


    );
  }
}

export default ImageUpload;

这是我的 uploadImages 组件:

import storage from "../Firebase/index";

async function uploadImages(imageList, path, progressCallback) {
    var promises = [];
    for(var i = 0; i < imageList.length; i++) {
        var image = imageList[i];
        promises.push(uploadImage(image, path, progressCallback));
    }
    return Promise.all(promises);
}

async function uploadImage(image, path, progressCallback) {
  progressCallback = progressCallback || function() {};

  return new Promise((resolve, reject) => {
      var task = storage.ref(`${path}${image.name}`).put(image);
      task.on("state_changed", progressCallback, reject, ()=>{
          resolve(task.snapshot.ref.getDownloadURL());
          console.log(image)
      });

  });
}

export default uploadImages;

抱歉,如果它是基本的东西,我是相当新的反应,这似乎令人费解。

代码更新:

import React, { Component } from "react";
import "../App.css"
import uploadImages from './uploadImages'
class ImageUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      images: [{
        id: '',
        image: '',
        url: '',
        progress: 0,
      }],
    };
  }
  handleChange = e => {
    if (e.target.files) {
      const images = e.target.files;
      this.setState(() => ({ images }));
      console.log(images)
    }
  };



  handleUpload = () => {
    if(this.state.images.length === 0) return;
    // I left out the "progress" method because doing a progress over multiple
    // files is a bit more tricky. But if you do want to do that, you'll have
    // to either get the total file size added together, or you'll have to
    // create a progress callback for each image being uploaded
    uploadImages(this.state.images, "images/", null).then(urls=>{
        // this is a list of urls, so you'll need to do something with that.
        this.setState( {url: urls[0]} );
        console.log(urls)
      });
  }

  render() {
    const divWithBackgroundImage = this.state && this.state.images.map(image =>
      <div style={{backgroundImage:`url(${this.state.images.url})`}} key={''}></div> )
    return (

      <div>
         <div className="file-field input-field">
          <div className="btn">
          <input type="file" multiple onChange={this.handleChange} />
        </div>
          <div className="file-path-wrapper">
            <input className="file-path validate" type="text" />
          </div>
    </div>
        <button
          onClick={this.handleUpload}
          className="additem"
        >
          Add Item
          </button>
        <br />
        <br />
        <main>
        <div className="grid">

        { divWithBackgroundImage }
          </div>
        </main>
      </div>
    );
  }
}

export default ImageUpload;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    也许要创建上传图片链接的状态数组,然后映射该数组?

    【讨论】:

    • 看到代码,我已经用上传的图片 url 更新了状态。
    • 您需要在 state 中创建图像数组: .... this.state = { images: [ { id: ' ';图片:''',网址:''。进度:0 },{ id:'',图片:''',url:''。进度:0 }, ... ], }; render() { //然后映射数组: const divWithBackgroundImage = this.state.images.map(image =>
      ) return ( ......
      { divWithBackgroundImage }
      ...... )} 类似的东西
    • 感谢您的评论,但是您的代码返回 images.map 不是函数的错误。
    • 我确实看到了您的目标,坦率地说,这就是我一直在做的事情,并且没有任何进展,因为即使使用 this.state && this.state.images.map 错误仍然存​​在。我现在已经更新了我的主要帖子。
    猜你喜欢
    • 2011-10-06
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2017-10-03
    相关资源
    最近更新 更多