0

当我在 iOS 设备上按下我的应用程序中的按钮时,我的控制台输出显示以下内容:

2019-09-22 13:45:25.116 [info][tid:com.facebook.react.JavaScript] 你点击了按钮

2019-09-22 13:45:25.116323-0400 AwesomeProject[5368:2651835] 你点击了按钮

我正在将“您点击按钮”记录到 onPressButton 函数内的控制台,每次按下按钮都会调用它两次。

这是我完整的 App.js 文件,该文件来自:https ://facebook.github.io/react-native/docs/handling-touches :

import React, { Component } from 'react';
import { Button, StyleSheet, View } from 'react-native';

export default class ButtonBasics extends Component {
  _onPressButton() {
    console.log('You tapped the button once!')
    alert('You tapped the button!')
  }

  render() {
    return (
      <View style={styles.container}>
          <View style={styles.buttonContainer}>
           <Button
             onPress={this._onPressButton}
             title="Press Me"
            />
         </View>
        <View style={styles.buttonContainer}>
          <Button
             onPress={this._onPressButton}
            title="Press Me"
            color="#841584"
           />
         </View>
        <View style={styles.alternativeLayoutButtonContainer}>
           <Button
            onPress={this._onPressButton}
            title="This looks great!"
           />
           <Button
            onPress={this._onPressButton}
            title="OK!"
            color="#841584"
           />
        </View>
       </View>
     );
   }
}

 const styles = StyleSheet.create({
   container: {
   flex: 1,
   justifyContent: 'center',
  },
  buttonContainer: {
     margin: 20
   },
   alternativeLayoutButtonContainer: {
    margin: 20,
    flexDirection: 'row',
    justifyContent: 'space-between'
   }
 });

我真的很茫然,为什么 onPressButton 在 iOS 上触发了两次,但在 Android 上却没有。

4

2 回答 2

2

尝试使用箭头功能

例子:-

onPress = {() => this.onPressButton()} //in Button

onPressButton = () => {                //onPressButton function
 console.log('You tapped the button');
}
于 2019-09-23T06:30:33.117 回答
1

https://snack.expo.io/r1OTvkEdS

如果您看一下小吃,您会发现它既没有记录也没有发出两次警报。javascript bundler可能与模拟器分开记录。这就是为什么在第一个日志上您会看到标记 [tid:com.facebook.react.JavaScript] 但在另一个日志上您会看到不同的标记。这是两个单独的接口记录相同的事情。你用什么来查看日志?您应该使用终端或反应调试工具。

TLDR:它没有触发两次,只是两个独立的记录器在做同样的工作。

于 2019-10-03T21:30:10.990 回答