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

Bas*_*hli 2 javascript react-native

我是 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>
    );
   }
  }
Run Code Online (Sandbox Code Playgroud)

And*_*lar 5

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

<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.
Run Code Online (Sandbox Code Playgroud)

对比

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

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

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