this.setState 不是函数(尝试上传图片)ReactJs

this.setState is not a function ( trying Upload Image) ReactJs

尝试使用 cropper 组件创建上传功能。但是当我尝试设置状态时,它说

Uncaught TypeError: this.setState is not a function at 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)

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

问题是您用于 onloadfunctionthis 没有您的 类 this。试试箭头函数:

reader.onload = () => this.setState({ image: reader.result })

或者在

之前将this赋给一个变量
const scope = this
reader.onload = function () {
  scope.setState({ image: reader.result })
}

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

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

渲染中:

<input onChange={this.loadFile}></input>

reader.onload 函数需要绑定到 this。然后它将在作用域上有 this.setState

var onloader = function(){this.setState({ image: reader.result }); reader.onload = onloader.bind(this);

你也可以只使用箭头函数:

reader.onload = ()=>{this.setState({ image: reader.result });