[英]React Native - binding a function to this
我使用反应原生0.48,我想知道以下是否可能。
所以我的目的是让我的代码更可重用。 我有4个类,每个类在componentDidMount中都有类似的代码。 它们共享类似的代码componentDidMount(),但render方法中的其余代码略有不同。
我的想法是跨类共享代码:
class 1
componentDidMount(){
componentDidMountTemplate().bind(this);
}
其中insideDidMountTemplate(它只是一个导出的函数),使用“this”关键字的代码应该对类1中的对象进行操作,或者基本上是任何调用和绑定它的类
但是行componentDidMountTemplate()。bind(this); 生成此错误:
不能将类作为函数调用
任何解决方案 想法?
你没有绑定任何东西,绑定方法返回一个新的实例,你没有将它存储在任何地方,并且最重要的是你没有在它自己的函数上运行绑定,而是你在该函数的返回值上做了你使用了()
并调用它。
我不确定你在代码中重复使用的是什么,因为你没有提供更多的细节,但基本上你根本不需要绑定它,只需将this
对象传递给外部函数。
所以你有两个主要选择:
componentDidMountTemplate
在任何情况下被声明为箭头函数,那么绑定将不起作用,因为箭头函数在词法上下文中使用this
(参见我的示例)。 这是一个小概念证明的片段:
class MyClass { externalFunc = ref => { console.log("passing the this explicit as a parameter", ref.state); }; externalFunc2() { // depending on bind and praying for the best! console.log("depending on bind ", this.state); } externalFunc3 = () => { // with arrow functions bind won't work //because `this` is bound in a lexical context console.log("arrow function", this.state); }; } const MyClassInstance = new MyClass(); class App extends React.Component { constructor(props) { super(props); this.state = { someValue: "123" }; this.externalFunc2 = MyClassInstance.externalFunc2.bind(this); this.externalFunc3 = MyClassInstance.externalFunc3.bind(this); } componentDidMount() { MyClassInstance.externalFunc(this); this.externalFunc2(); this.externalFunc3(); } render() { return ( <div> <div>Look at the console!</div> </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
您可以使用类属性并将componentDidMount
定义为componentDidMount
的箭头函数(而不是方法)。 箭头函数使用lexical this
,因此您不必费心使用函数绑定。 例如:
componentDidMount = () => {
// you can access `this` safely
}
componentDidMountTemplate().bind(this);
应该是
this.componentDidMountTemplate = componentDidMountTemplate.bind(this);
.bind()
返回一个新的绑定函数。 您需要将该函数存储在一个值中,然后调用它。
现在你可以调用this.componentDidMountTemplate()
此外,只要你在函数旁边写()
,就会调用该函数
您可以绑定该函数,然后立即调用它,如下所示:
componentDidMount() {
(componentDidMountTemplate.bind(this))();
}
它由两部分组成 - 首先,将组件上下文绑定到函数( .bind(this)
),然后再调用返回的函数。
你得到的错误是可疑的。 虽然你似乎错误地使用bind
我会期望错误: Cannot read property 'bind' of undefined
你的componentDidMountTemplate
是一个类吗? 我假设你想把它改成一个函数,然后按照下面关于bind
的建议。
如果你要调用的绑定功能,你需要的()
后bind()
否则,您正在调用未绑定的函数,然后尝试绑定从它返回的任何内容。
componentDidMount(){
componentDidMountTemplate.bind(this)();
}
这意味着创建了一个新的绑定函数,然后立即调用
正如许多其他答案所暗示的那样,React组件通常最初绑定函数并存储对绑定函数的引用。 但是在您的情况下,您可能只调用一次,因为componentDidMount
生命周期方法只调用一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.