javascript - 可触摸的不透明度功能在应用程序启动时立即调用
问题描述
我是 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>
);
}
}
解决方案
发生这种情况是因为您按照自己的方式在渲染时立即调用该函数。
<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()
实际传递一个函数。通过按下按钮,您正在调用您传递给它的函数。
推荐阅读
- npm - 从 gitlab 项目内部安装 NPM
- javascript - 将输入类型中 Form.Item 的默认按键行为更改为 onChange(制表符)
- r - 对矩阵行进行排序和去排序的最快方法 [r]
- java - flyway迁移中的多个更改脚本不起作用
- azure - azure log analytics - concat two graphs in log analytics
- openoffice-writer - 如何在openoffice中按样式提取文本
- clojure - Clojure“反复”让“未来”按顺序运行
- css - FontAwesome 图标在基于 chromium 的浏览器上根本不显示
- angular - 从服务获取数据时数据不会更新..当用户单击图标时,数据将被发送到服务和另一个
- javascript - 使用 JavaScript 提取 .xsn 扩展名文件