如何通过OnSubmit()而不是reactjs中的OnChange()渲染图像

时间:2017-12-22 17:12:43

标签: reactjs

我的目的是选择一个图像文件然后再渲染图像,只需单击另一个按钮。我试图存储以跨组件存储事件值(文件路径)但无法执行此操作。有更简单的方法吗? 我无法弄清楚如何从OnChange()函数中的event.target.files存储文件,并在OnSubmit()事件中使用它。我目前的代码段如下:

handleIMageChange(event) {
    let reader = new FileReader();
    let file = event.target.files[0];

    reader.onloadend = () => {
      this.setState({
        file: file,
        reader
      });
    }
}

handleImgSubmit(event){
  let reader = new FileReader();

  reader.onloadend = () => {
  this.setState( prevState => {
  return {
    file: prevState.file,
    imagePreviewUrl: prevState.reader.result
  }
  })
  }
  alert(this.state.file);
reader.readAsDataURL(this.state.file);
event.preventDefault();
}

render(){
  return(
  <div className="pagecontainer">
  <MuiThemeProvider muiTheme={ myTheme }>

  <div className="column2">
  <input type="file" id="myimage" onChange={this.handleIMageChange.bind(this)} />
  <input type="submit" value="upload" onClick={this.handleImgSubmit}/>

  {this.state.value}
  <Image  src={this.state.imagePreviewUrl} />
  </div>

提前致谢,

1 个答案:

答案 0 :(得分:0)

对于您正在设置imagePreviewUrl的handleImageChange函数,您只需将读取器类输出保存到状态和提交更改时的属性更新imagePreviewUrl

genotype <- data.frame(position = 1:3,
                       mutation = c("C > A", "+TGCA", "-ACGT"))
genotype$mutation_type <- 
    ifelse(grepl("\\+", genotype$mutation), "Insertion", 
           ifelse(grepl("\\-", genotype$mutation), "Deletion", "SNP"))

  position mutation mutation_type
1        1    C > A           SNP
2        2    +TGCA     Insertion
3        3    -ACGT      Deletion