gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:34:36 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com