为什么我们需要在React Native中绑定函数? [英] Why we need to bind function in React Native?

查看:62
本文介绍了为什么我们需要在React Native中绑定函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个React Native项目.在一些教程中,我看到了绑定这样的方法:

I am working on a React Native project. On some tutorials I have seen to bind a method like this:

constructor(props){
super(props);
this.my_function = this.my_function.bind(this);
}

我的问题是,是否可以使用 this.my_function 访问构造函数中的函数,那为什么还要再次绑定它?我有Java和Python的背景,也许这就是为什么我对这种类型的方法绑定感到困惑的原因.注意:我知道,如果我没有在React Native/React JS中绑定方法,那么我的方法将无法正常工作.我只想知道为什么我需要这种额外的绑定.

My question is if I can access the function in constructor using this.my_function then why I need to bind this again? I have Java and Python background, may be that's why I am confused with this type of method binding. Note: I know that if I don't bind a method in React Native/React JS my method won't work correctly. I just want to know why I need this extra binding.

推荐答案

看看此链接以了解JS闭包的工作原理

Take a look at this link to understand how JS closure works

http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

您需要绑定该函数,以便它可以访问类中的状态和其他变量,而不仅仅是执行时传递的参数.

You need to bind the function so it has access to state and other variables in your class, not just parameters that pass when you execute.

这篇关于为什么我们需要在React Native中绑定函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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