React Native 组件回调函数 [英] React Native component callback functions

查看:48
本文介绍了React Native 组件回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在组件中,我见过不同的回调方式.有什么区别:

In components, I've seen different way of doing callbacks. What is the difference between:

<MyButton onPress={ () => {doSomething(data)} }>

<MyButton onPress={ this.doSomething.bind(this) }>

推荐答案

{doSomething(data)} }>

这个代码块使用了 ES6 Arrow 函数;这是在 javascript 中声明函数的另一种方式.此外,箭头函数中 this 的范围取决于函数的创建位置,而不是 this 的正常范围规则,默认情况下取决于函数的调用方式.

This code block uses the ES6 Arrow function; which is another way of declaring a function in javascript. Also, the scope of this in arrow function depend where the function was created as opposed to normal scoping rule of this which by default depends on how the function was called.

该语句调用 doSomething 方法.但是由于事件注册是在不同的元素上完成的,所以doSomething的Scope不同,通过javascript中的bind方法强制绑定.

This statement makes a call to doSomething method. But since the event registration is done on different element, the Scope of doSomething is different and is forcefully binded by using bind method in javascript.

此外,在第二种方法中,您没有传递数据参数,您可以使用第二个参数将其传递给如下所示的方法.

Also, in the second method you are not passing the data parameter, which you can pass using the second argument to the method like shown below.

这篇关于React Native 组件回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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