How to bind 'this' to functions outside react class which is a callback from other component?

后端 未结 2 607
臣服心动
臣服心动 2021-01-28 11:04

I have a React Component such as :

function callback(params){..
// I need to use this.setstate but this callback function is called 
// from other component. How         


        
相关标签:
2条回答
  • 2021-01-28 11:42

    I don't really understand the question. I don't know if this is what you mean, but if you want to save the 'this' temporary variable, then just create a global array or single variable to store the 'this'.

    var thisTemp;
    
    function callback(params){..
    // use variable here
    thisTemp.blah();
    ...
    }
    
    class RespProperties extends Component { ..
    //Assign this to thisTemp
    thisTemp = this;
    ...
    }
    
    0 讨论(0)
  • 2021-01-28 11:54

    You could separate this shared function, leaving it outside the components, then use bind:

    function callback(params){
        this.setState({ works: true });
    }
    
    class RespProperties extends Component {
        state = { works: false }
        ...
        render = () => <button onClick={callback.bind(this)}>Click</button>
                                     // ^ here we use .bind(this) to... well...
                                     //   bind `this` so we can use it in the function xD
    }
    
    class SomeOtherComponent extends Component {
        state = { works: false }
        ...
        render = () => <button onClick={callback.bind(this)}>I'm from some other component</button>
    }
    
    0 讨论(0)
提交回复
热议问题