React dropzone图像未在模板上更新

时间:2016-06-23 14:28:33

标签: javascript reactjs

我已经使用react dropzone组件进行多个图像上传,但我的模板上没有显示图像预览。文件显示在控制台上。我做错了什么?我在这里使用了这个组件https://github.com/okonet/react-dropzone。让我知道我还需要提供什么来用细齿梳检查这个问题。提前感谢您的帮助。我们将非常感谢您的帮助。

import React from 'react';
import Dropzone from 'react-dropzone';

export default class DropzoneDemo extends Dropzone {
  constructor(props) {
    super(props);
    this.state = {
      files: [],
      style: {},
    };
  }

  componentDidMount() {
    this.state.style = {
      backgroundImage: (`url(${this.props.img})`),
    };
    this.state.files = [];
  }

  componentDidUpdate() {
    if (this.state.files.length) {
      this.state.style = {
        backgroundImage: (`url(${this.state.files[0].preview})`),
      };
    } else {
      this.state.style = {
        backgroundImage: (`url(${this.props.img})`),
      };
    }
  }

  onDrop(files) {
    console.log(this.state.files);
    this.state.files = files;
  }

  render() {
    const emptyStyle = {
      backgroundImage: 'none',
    };
    return (
      <div>
        <Dropzone onDrop={this.onDrop} style={emptyStyle} >
          <div className='wrap-to-drag-img' style={this.state.style}></div>
        </Dropzone>
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

不要在React

中直接更新this.state
this.state.style = { // this is bad
        backgroundImage: (`url(${this.state.files[0].preview})`),
      };

将样式设置为render()而不是

render() {
  const bgImage = this.state.files.length ?             
       `url(${this.state.files[0].preview})` :
       `url(${this.props.img})`;
  const bgStyle = {
     backgroundImage: bgImage
  };

  const emptyStyle = {
    backgroundImage: 'none',
  };
  return (
    <div>
      <Dropzone onDrop={this.onDrop} style={emptyStyle} >
        <div className='wrap-to-drag-img' style={bgStyle}></div>
      </Dropzone>
    </div>
  );
}

答案 1 :(得分:0)

 onDrop(files) {
    this.state.files = files;
    console.log(files[0].preview);
    const bgImage = this.state.files.length ?
      `url(${this.state.files[0].preview})` :
      `url(${this.props.img})`;
    const bgStyle = {
      backgroundImage: bgImage,
    };
    const emptyStyle = {
      backgroundImage: 'none',
    };
    const dropzone = document.getElementById('dropzone');
    ReactDOM.render(<div id='dropzone'><Dropzone onDrop={this.onDrop} style={emptyStyle} >
      <div className='wrap-to-drag-img' style={bgStyle}></div>
    </Dropzone></div>, dropzone);
  }