RN学习

一、新建项目

1、安装react环境

Yarn是 Facebook 提供的替代 npm 的工具,可以加速 node 模块的下载。React Native 的命令行工具用于执行创建、初始化、更新项目、运行打包服务(packager)等任务。
npm install -g yarn react-native-cli

2、初始化项目

因为npm的服务器是架在国外的 , 在国内的访问速度不行 , 为了提高npm的下载速度 , 我们可以使用淘宝的npm镜像. 
执行下面两条命令应该就可以解决初始化项目时这个报错. 
npm config set registry https://registry.npm.taobao.org 
npm config set disturl https://npm.taobao.org/dist
react-native init 项目名

3、连接安卓机:

模拟器:adb connect 127.0.0.1:21503
真机:adb connect 127.0.0.1:5307

4、启动项目

react-native run-android

二、获取地理位置

1、添加权限

iOS
你需要在Info.plist中增加NSLocationWhenInUseUsageDescription字段来启用定位功能。如果你使用react-native init创建项目,定位会被默认启用。
Android
要请求访问地理位置的权限,你需要在AndroidManifest.xml文件中加入如下一行:

< uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />

在这里插入图片描述

2、编写代码

在核心代码区添加代码
在这里插入图片描述

componentDidMount() {
        //获取地理位置
        navigator.geolocation.getCurrentPosition(
            (coords) => {
                this.setState(coords);
                console.log(coords)
            },
            (error) => console.error(error)
        );
        //持续监听位置,每当位置变化调用success回调.
        this.watchID = navigator.geolocation.watchPosition((lastPosition) => {
            this.setState({lastPosition});
        });
    }

在显示区添加代码
在这里插入图片描述
代码:

<Text>纬度:{this.state.coords?this.state.coords.latitude:'获取中'}</Text>
<Text>经度:{this.state.coords?this.state.coords.longitude:'获取中'}</Text>

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38457055/article/details/89024411