Skip to content

Bind ES6 class methods in constructor #69

@klimashkin

Description

@klimashkin

Seems like binding class methods in ES6 class constructor doesn't work with react-transform-hmr (which uses react-proxy)

class Test extends Component({
  constructor(props) {
    super(props);
    this.state = {open: false};
    this.handleMouseDown = this.handleMouseDown.bind(this);
    window.testInstance = this;
  }
  handleMouseDown() {
    console.log(window.testInstance === this); // false
    this.setState({open: true}); // Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the  component.
  }
  render {
    return <div onMouseDown={this.handleMouseDown}>Test</div>;
  }
})

Binding in componentWillMount works:

class Test extends Component({
  constructor(props) {
    super(props);
    this.state = {open: false};
  }
  componentWillMount() {
    window.testInstance = this;
    this.handleMouseDown = this.handleMouseDown.bind(this);
  }
  handleMouseDown() {
    console.log(window.testInstance === this); // false
    this.setState({open: true}); // Ok
  }
  render {
    return <div onMouseDown={this.handleMouseDown}>Test</div>;
  }
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions