如何将“this"绑定到作为其他组件回调的反应类之外的函数? [英] How to bind 'this' to functions outside react class which is a callback from other component?

查看:26
本文介绍了如何将“this"绑定到作为其他组件回调的反应类之外的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 React 组件,例如:

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 do I bind value of this here 
// 'this' of RespProperties
...
}

class RespProperties extends Component { ..
 ...
}

这个回调函数是从其他组件调用的.如何在此处绑定this"的值,以便它可以使用此组件的状态?

This callback function is called from some other component. How do I bind value of 'this' here so that it can use states of this component?

推荐答案

你可以把这个共享函数分开,把它留在组件之外,然后使用bind:

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>
}

这篇关于如何将“this"绑定到作为其他组件回调的反应类之外的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆