Mystery of “this” in ReactJS

后端 未结 1 1562
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 00:03

I am fairly new to the Facebook\'s React world. Their documentation seems to be very good but there are a few areas where I need a little bit of clarity. This is one of th

相关标签:
1条回答
  • 2020-12-07 00:35

    There's no mystery of "this" that is specific to ReactJS.

    This is just a case of standard scoping issues that crop up with callbacks in JavaScript.

    When you're in a react component, all methods on the base component will be scoped with the this being the current component, just like any other JavaScript "class".

    In your snippet you have a render method which is a function on the base component and therefore this is equal to the component itself. However within that render method you're calling a callback with this.props.clist.forEach, any function callbacks inside the render method will need to be either bound to the correct this scope, or you can do var that = this (although this is an anti-pattern and should be discouraged)`.

    Example, slightly simplified version of your snippet:

    var MyComponent = React.createClass({
        handleCompanyRemove: function(e) {
            // ...
        },
        render: function() {
            // this === MyComponent within this scope
    
            this.props.someArray.forEach(function(item) {
                // this !== MyComponent, therefore this.handleCompanyRemove cannot
                // be called!
            })
        }
    })
    

    As you can see from the comments above, inside your callback for the .forEach you cannot use this directly without either defining a variable outside, or properly binding the function.

    Other options to solve this are:

    Binding the callback function to the correct this scope. Example:

    this.props.someArray.forEach(function(item) {
        // this === MyComponent within this scope too now!
        // so you can call this.handleCompanyRemove with no problem
     }.bind(this))
    

    If you're using Babel/ES6 you can use the Fat Arrow function syntax which guarantees that this scope continues to the callback from the parent scope. Example:

    this.props.someArray.forEach((item) => {
        // this === MyComponent within this scope too now!
        // so you can call this.handleCompanyRemove with no problem
    })
    
    0 讨论(0)
提交回复
热议问题