简体   繁体   中英

In React project, “this” converts into “undefined”

A very simple code

var App = React.createClass({
    handleForm: (e) => {
        e.preventDefault();
    },
    render: () => {
        return (
            <form>
                <button type="submit" onClick={this.handleForm}>Go</button>
            </form>
        );
    }
});

Gets converted into

// ...
_react2['default'].createElement(
    'button',
    { type: 'submit', onClick: undefined.handleFormSubmit },
    'Go'
)

But why? And do I need to bind all the things explicitly (including this.setState which I can't get working for the same reason)?

I'm using react 0.13.3 with webpack 1.12.2 and babel-loader 5.3.2. Haven't faced such a problem before.

When you use an arrow function as the value of a property in an object literal, the binding to this is that of the function's declaration scope just like any arrow function. In ES6 module code the value of this in the outermost context is defined to be undefined so Babel is simply inlining this value. What you want to do is this:

var App = React.createClass({
  handleForm(e) {
    e.preventDefault();
  },
  render() {
    return (
        <form>
            <button type="submit" onClick={this.handleForm}>Go</button>
        </form>
    );
  }
});

As a final note, you do not need to bind any member functions when using React.createClass as React will do this for you automatically and in a more efficient way than with Function.prototype.bind .

Thank you @loganfsmyth for the update about why this is undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM