javascript - 可触摸的不透明度功能在应用程序启动时立即调用

标签 javascript react-native

我是 js 的新手并且 react native 。我对下面的代码有疑问。作为可触摸不透明度的 onpress 属性值给出的函数在应用程序启动时调用,而无需触摸可触摸不透明度。任何人都可以解释屏幕后面发生的事情。有关详细信息,请参阅 hello 方法的内联注释。

export default class FirstClass extends Component {  

  hello(){  // this function is called at launch of application 
            // itslef .I know if i can use fat arrow function or 
            // bind function to invoke this wont call at the start 
            // of application.Can anyone explain why its calling
            // automatically in this case and what is the this 
            // refers to in this method in this case.
    console.log('Hai from method hello');
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.hello()}>
          <Text>FirstScreen</Text>    
        </TouchableOpacity>
      </View>
    );
   }
  }

最佳答案

发生这种情况是因为您按照您的方式在渲染时立即调用该函数。

<TouchableOpacity onPress={this.hello()}> // This means you are directly invoking the function when the component renders. It is called as soon as the render happens.

对比

<TouchableOpacity onPress={() => this.hello()}> // You are referencing a function to React to call later when the actual event happens.

另一种说法是:onPress 需要一个函数,对吗?您没有传递函数,因为在您的情况下 this.hello() 不返回函数。您只需调用该函数即可。这发生在渲染时。

第二种方式:() => this.hello()其实是传递了一个函数。通过按下按钮,您将调用传递给它的函数。

关于javascript - 可触摸的不透明度功能在应用程序启动时立即调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52700620/

相关文章:

javascript - 本地滚动切换

javascript - 将扫描条形码的类型或数据写入 REACT-NATIVE 上的文本输入中

react-native - 如何在 React Native 中为函数计时?

java - (React Native/Android) Android getFilesDir() 给我 '/data/user/' 而不是 '/data/data/'

react-native - 是否可以在 react-native-router-flux 中向 NavBar 添加自定义按钮?

javascript - 使用全选或单独选择多个复选框

javascript - Wikitude 地理定位不更新 POI 标记 Wikitude 示例

javascript - 如何使隐藏(ng-cloaked)元素保留其可见时占用的空间

npm - 构建和分发扩展 iOS 功能的 React Native iOS 组件的好方法是什么?

javascript - 打印时如何启用所有禁用