Get image preview before uploading in React

前端 未结 9 1728
醉梦人生
醉梦人生 2020-12-04 17:51

Many examples of this on here but can\'t seem to find any for react. I have managed to convert the vanilla js to react but getting an error.

The answer looks simple

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 18:38

    No difference, just read your image when the load event finishes. After the load end event handler just set your state:

    getInitialState: function(){
      return{file: []}
    }
    
    _onChange: function(){
      // Assuming only image
      var file = this.refs.file.files[0];
      var reader = new FileReader();
      var url = reader.readAsDataURL(file);
    
       reader.onloadend = function (e) {
          this.setState({
              imgSrc: [reader.result];
          })
        }.bind(this);
      console.log(url) // Would see a path?
      // TODO: concat files
    },
    
    render: function(){
     return(
      
    {/* Only show first image, for now. */}
    ) }

提交回复
热议问题