首页 > 解决方案 > 可触摸的不透明度功能在应用程序启动时立即调用

问题描述

我是 js 的新手并做出原生反应。我对下面的代码有疑问。作为可触摸不透明度的 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>
    );
   }
  }

标签: javascriptreact-native

解决方案


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

<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()实际传递一个函数。通过按下按钮,您正在调用您传递给它的函数。


推荐阅读