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

后端 未结 2 610
臣服心动
臣服心动 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: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 = () => 
                                     // ^ 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 = () => 
    }
    

提交回复
热议问题