在React中上传之前获取图像预览 [英] Get image preview before uploading in React

查看:81
本文介绍了在React中上传之前获取图像预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有许多示例,但似乎找不到任何反应。我已经设法将普通js转换为做出反应,但

解决方案

没什么区别,只需在 load 事件结束时读取图像。在加载结束事件处理程序之后,只需设置您的状态:

  getInitialState: function(){
return {file:[]}
}

_onChange:function(){
//仅假设图片
var file = this.refs.file.files [0];
var reader = new FileReader();
var url = reader.readAsDataURL(file);

reader.onloadend =函数(e){
this.setState({
imgSrc:[reader.result];
})
}。绑定(this);
console.log(url)//会看到路径吗?
// TODO:concat文件
},

渲染:function(){
return(
÷ div>
<形式>
<输入
ref =文件
type =文件
name = user [image]
multiple = true
onChange = {this_onChange} />
< / form>
{/ *目前仅显示第一张图像。* /}
< img src = {this.state .imgSrc} />
< / div>

}


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 enough so here I go in react:

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);
  console.log(url) // Would see a path?
  // TODO: concat files for setState
},

render: function(){
 return(
  <div>
    <form>
      <input 
        ref="file" 
        type="file" 
        name="user[image]" 
        multiple="true"
        onChange={this._onChange}/>
     </form>
    {/* Only show first image, for now. */}
    <img src={this.state.file[0} />
  </div>
 )
};

Basically all answers I have seen show something like what I have. Any difference in React app?

Regarding answer:

解决方案

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(
  <div>
    <form>
      <input 
        ref="file" 
        type="file" 
        name="user[image]" 
        multiple="true"
        onChange={this_onChange}/>
     </form>
    {/* Only show first image, for now. */}
    <img src={this.state.imgSrc} />
  </div>
 )
}

这篇关于在React中上传之前获取图像预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆