javascript - 如何获取 <TouchableOpacity> 内的类范围

标签 javascript reactjs react-native

我在 React Native 中有一个带有 onPress 事件的按钮。

我想要全类同学都这样

这是我的代码:

        <TouchableOpacity onPress={this.onFBLoginButtonPress}>
          <View>
            <Text>Sign In with Facebook</Text>
            <Image source={FBImg} />
          </View>
        </TouchableOpacity>

我尝试过 onPress={() => this.onFBLoginButtonPress}

但这会导致按钮无法实际处理。

如何在不破坏按钮的情况下传递整个类的 this?

最佳答案

onPress={() => this.onFBLoginButtonPress} 缺少尾随括号,因此它实际上并未调用该方法。应该是 onPress={() => this.onFBLoginButtonPress()}

I didn't know you needed the parenthesis when you used an arrow function, as you don't without it

您正在传递一个要调用的函数。 this.onFBLoginButtonPress 一个函数,所以你不需要括号。但是你原来的箭头函数:

() => this.onFBLoginButtonPress

相当于:

function () {
  return this.onFBLoginButtonPress;
}

返回函数但不调用它。

<小时/>

为什么箭头函数起作用而传递 this.onFBLoginButtonPress 不起作用:

一般来说,函数内的作用域 (this) 被设置为调用它的对象。所以考虑一下:

foo.doSomethingCool();

doSomethingCool 内部,this 将被设置为 foo,因为它是作为 foo 上的方法调用的.

但是,如果将方法与对象分离,则不会设置范围:

foo.doSomethingCool() // scope === foo

const cool = foo.doSomethingCool;
cool(); // scope === undefined

这实际上就是您将 this.onFBLoginButtonPress 作为事件处理程序传递时所做的事情:

<TouchableOpacity onPress={this.onFBLoginButtonPress}>

您正在传递函数本身,该函数将被单独调用:

// Inside the component receiving the handler prop
// it's just an ordinary function
const {onPress} = this.props;
onPress(); // no scope

您可以通过使用 function.bind 显式设置范围来解决此问题:

// create a copy of onFBLoginButtonPress that's explicitly bound to 'this'
<TouchableOpacity onPress={this.onFBLoginButtonPress.bind(this)}>

您在箭头函数中没有看到此问题的原因是因为箭头函数 use the enclosing scope :

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

所以当你这样做时:

onPress={() => this.onFBLoginButtonPress()}
处理函数内的

this 预先绑定(bind)到声明该函数的任何 this 位置。因此,即使单独调用,您也可以获得正确的范围:

// Inside the component receiving the handler prop
// it's just an ordinary function
const {onPress} = this.props;
onPress(); // arrow function's 'this' is already bound

希望这有帮助。

关于javascript - 如何获取 <TouchableOpacity> 内的类范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57882108/

相关文章:

javascript - 使用 Sequelize 按相关关键字查找所有图像,并包含要包含/排除的关键字 ID 值数组

javascript - 每次收到 XHR 请求时,如何使用 JQuery AjaxSetup 将 "csrf"设置为参数?

reactjs - React 中的单向数据流

javascript - React Transition Group 向上滑动元素

javascript - javascript/nodeJs 中的两个递归函数和计算器错误。了解差异

javascript - 在 redux-orm 模式实例上使用 reducer 方法

javascript - React-native 选择器默认值

javascript - React-Native 获取,网络请求失败。不使用本地主机

reactjs - 如何在 AWS Amplify GraphQL 客户端中进行过滤

javascript - native $ 函数应该是什么?