this.setState不是一个函数(尝试上传图像)ReactJs

Его*_*нко 2 javascript image-upload reactjs

尝试使用裁纸器组件创建上传功能。但是当我尝试设置状态时说

未捕获的TypeError:this.setState不是FileReader.reader.onload的函数

零件

import React, { Component, PropTypes } from 'react'
import { Link, browserHistory } from 'react-router'
import { connect } from 'react-redux'
import Cropper from 'react-cropper';

class HeadPortrait extends Component {
  constructor(props) {
    super(props)
    this.state = {
      image: '',
    }
  }

  clickadd(e) {
    document.getElementById('uploadfiles').click();
  }

  loadFile(e) {
    e.preventDefault();
    var reader = new FileReader();
    reader.onload = function () {
      this.setState({ image: reader.result })
    };
    reader.readAsDataURL(e.target.files[0]);
    ;
  };

  _crop() {
    // image in dataUrl
    console.log(this.refs.cropper.getCroppedCanvas().toDataURL());
  }

  render() {
    return (
      <div className="group-content width415">
        <input id="uploadfiles" type="file" accept="image/*" onChange={this.loadFile.bind(this)}></input>
        <a onClick={this.clickadd.bind(this)} className="gt-btn-small gt-left ">Add Image</a>
        <div>
          <div className="bigImageprev gt-left"><img width="300" height="300" id="output" /></div>
        </div>
        <div className="gt-clear"></div>
        <div className="btnSaveImage gt-right"><a className="gt-btn-small" href="#">Save</a></div>

        <Cropper
          ref='cropper'
          src={this.state.image}
          style={{ height: 400, width: '100%' }}
          // Cropper.js options
          aspectRatio={16 / 9}
          guides={false}
          crop={this._crop.bind(this)} />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    // stories: state.stories
  }
}

export default connect(mapStateToProps)(HeadPortrait)
Run Code Online (Sandbox Code Playgroud)

尝试像示例https://github.com/roadmanfong/react-cropper/blob/master/example/src/Demo.jsx

Bal*_*des 8

问题是function您使用的是onloadthis没有您的课程this。尝试使用箭头功能:

reader.onload = () => this.setState({ image: reader.result })
Run Code Online (Sandbox Code Playgroud)

或先分配this给变量

const scope = this
reader.onload = function () {
  scope.setState({ image: reader.result })
}
Run Code Online (Sandbox Code Playgroud)

同样值得将事件处理程序绑定到构造函数中,而不是直接绑定到render中,因为这样一来,无论状态如何变化,您都将重新渲染组件-因为事件处理程序每​​次都是新的引用:

constructor(props) {
  super(props)
  this.state = {
    image: '',
  } 
  this.loadFile = this.loadFile.bind(this) // properly bound once
}
Run Code Online (Sandbox Code Playgroud)

在渲染中:

<input onChange={this.loadFile}></input>
Run Code Online (Sandbox Code Playgroud)