如何仅在用户按下 React Native 中的按钮后获取位置

How to get location only once use has pressed button in ReactNative

我是 React Native 的新手。我试图在用户单击按钮后获取用户的地理位置。代码如下:

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

class TestScreen extends Component {
    constructor(props) {
        super(props);

        this.state = {
            latitude: null,
            longitude: null,
            error: null,
        };
    }


    getLocation() {

        navigator.geolocation.getCurrentPosition(
            (position) => {
                this.setState({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    error: null,
                });
            },
            (error) => this.setState({ error: error.message }),
            { enableHighAccuracy: true, timeout: 20000},
        );
    }

    render() {
        return (
            <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Button onPress={this.getLocation()} title="Get Location"/>        
            <Text>Latitude: {this.state.latitude}</Text>
            <Text>Longitude: {this.state.longitude}</Text>
            {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
            </View>
        );
    }
}
export default TestScreen;

加载屏幕后,地理位置会立即输出到屏幕我希望用户能够单击按钮,然后才能输出地理位置。其次,我已经看到许多地理定位的实现都使用 componentDidMount,在这种情况下我需要使用它吗?

谢谢

旧代码

<Button onPress={this.getLocation()} title="Get Location"/>

新变化:

<Button onPress={()=>this.getLocation()} title="Get Location"/>

对于当前位置,您寻找的解决方案如下所示,它对我有用。

_this.watchID = navigator.geolocation.watchPosition((position) => {
            console.log(TAG + "position : " + JSON.stringify(position));
            var gps_location = position.coords.latitude + "," + position.coords.longitude;
            console.log(TAG + "gps_location : " + JSON.stringify(gps_location));
          }, error => {
            console.log(TAG + " error in getting location " + error);            
          }, {
              enableHighAccuracy: false, timeout: 20000, maximumAge: 1000
            });