【问题标题】:React Native component callback functionsReact Native 组件回调函数
【发布时间】:2017-01-16 16:20:03
【问题描述】:

在组件中,我看到了不同的回调方式。有什么区别:

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

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

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    &lt;MyButton onPress={ () =&gt; {doSomething(data)} }&gt;

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

    &lt;MyButton onPress={ this.doSomething.bind(this) }&gt;

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

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

    &lt;MyButton onPress={ this.doSomething.bind(this, data)} }&gt;

    【讨论】:

      【解决方案2】:
      <MyButton onPress={ () => {doSomething(data)} }>
      

      正在调用一个新的匿名函数onPress,它将运行doSomething

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

      正在调用对已在类中定义的命名函数的引用。只有在使用类函数(我的意思是非 ES6 箭头函数)时才需要绑定到 this。

      const doSomething = () => { ... }
      

      不需要.bind(this),因为箭头函数绑定在lexical scope

      你一定要仔细阅读What is the best and most efficient way to bind callbacks in ReactJS? In the constructor or in the render method or as a property initializer?

      【讨论】:

        猜你喜欢
        • 2021-07-15
        • 1970-01-01
        • 2020-11-02
        • 2016-12-26
        • 1970-01-01
        • 2019-05-30
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多