React03 移动端跨平台开发

目录

React-day03 RN移动端开发

了解React-Native

Facebook发起的开源的一套新的APP开发方案,Facebook在当初深入研究Hybrid开发后,觉得这种模式有先天的缺陷,所以果断放弃,转而自行研究,后来推出了自己的“React Native”方案,不同于H5,也不同于原生Native,更像是用JS写出原生应用

  • 优点
  1. 开发成本小于Native模式 Andriod-Java-Kotlin IOS-OC-Swift

  2. 性能体验高于Hybrid

  3. 一次学习,跨平台开发Android和iOS, 小程序

  4. 社区繁荣

  • 缺点
  1. 不同平台代码有所区别
  2. 开发人员学习有一定成本
  • 几种开发技术对比应用质量开发效率的平衡折衷的结果

了解React-Native工作流程

  1. 项目开发:使用Node初始化项目(需要安装Node),使用JavaScript/JSX语言开发
  2. 语言翻译:Python, C++将js翻译成java代码(需要安装Python2)
  3. 代码编译:Android-SDK将java编译成字节码(二进制),打包成可安装的apk(需要JDK8 & Android-SDK)
  4. 安装运行:通过Adb工具,把apk运行到Android模拟器

创建第一个React-Native项目 *

  • 安装脚手架react-native-cli 同时安装新的版包管理工具

    npm install -g yarn react-native-cli

  • 创建项目:doubanMovie(在不包含中文的目录执行)

    react-native init xxx --version [email protected]

  • 运行项目

    • 打开USB调试, 配置SDK

      • ANDROID_HOME=G:\Android-SDK
      • PATH=%PATH%;%ANDROID_HOME%\platform-tools
      • adb devices查看已连接设备
    • 连接模拟器: adb connect 127.0.0.1:62001

    • 更改gradle路径doubanMovie\android\gradle\wrapper\gradle-wrapper.properties

      • distributionUrl值修改为file\:///E:/Lesson/bc1/React/day03/Resource/gradle-2.14.1-all.zip 直接复制过来的路径要把反斜线\改成正斜线/
    • 在项目根目录执行react-native run-android

      运行期间会开启一个Node服务,不要关闭

    • 第一次运行报错,需要在设备上设置app的Node服务地址

      解决方式: 打开app > 菜单按钮 > Dev Settings -> Debug server host ...

      填写服务ip和端口号, 注意冒号用英文半角,重启服务,重启应用

了解React-Native项目及结构

  • 目录结构
    • index.js 项目入口文件
    • App.js 项目根组件,用户看到的首页组件
    • package.json 项目配置文件
    • app.json 配置项目名称
  • React-Native与React对比

    • 组件写法

      RN提供View,Text组件,没有html的dom元素

      View -> div 布局容器

      Text -> p 显示文字

    • 样式写法

      使用const styles = StyleSheet.create({...})

  • React-Native平台相关代码处理

    const instructions = Platform.select({
      ios: 'Press Cmd+R to reload,\n Cmd+D or shake for dev menu',
      android: 'Double tap R on your keyboard to reload,\n',
    });

开发资料

  • 官方文档
    • 环境初始化:https://facebook.github.io/react-native/docs/getting-started.html
    • 组件及APIs:https://facebook.github.io/react-native/docs/components-and-apis.html
  • 中文文档
    • 环境初始化:https://reactnative.cn/docs/0.51/getting-started.html#content
  • 技术博客
  • 在github.com搜索react
    • https://github.com/poplartang 在Stars 搜索React

项目开发

路由(react-native-router-flux)

  • react-native-router-flux

  • 源码地址:https://github.com/aksonov/react-native-router-flux

    应用场景:在RN项目中进行路由跳转时使用

    安装方式:yarn add react-native-router-flux

  • 使用:

    Router(路由): 一般写在项目的根组件

    Stack (栈):给Scene场景提供容器

    Scene(场景):设置路由跳转规则

    Actions (动作):触发路由跳转

    const App = () => (
      <Router>
        <Stack key="root">
          <Scene key="login" component={Login} title="Login"/>
          <Scene key="register" component={Register} title="Register"/>
          <Scene key="home" component={Home}/>
        </Stack>
      </Router>
    );

    注意事项:

  • 最新版的react-native-router-flux会在react-native 0.55.4版本出现isMounted(...)警告,可在App.js添加以下代码忽略警告。随后两个框架更新后,此警告也可消除。

    import { YellowBox } from 'react-native'
    YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated'])
  • 触发路由:三种方式 (注意导入Actions组件)

    <Text onPress={Actions.movieList}>电 影</Text>
    <Text onPress={() => { Actions.movieList()}}>电 影</Text>
    <Text onPress={() => { Actions['about'].call() }}>关 于</Text>
  • 弹性布局参考: http://www.runoob.com/w3cnote/flex-grammar.html

开发组件(swiper)

  • 开源轮播图react-native-swiper

  • 源码地址:https://github.com/leecade/react-native-swiper

    应用场景:在首页展示轮播图

    安装方式:yarn add react-native-swiper

  • 常用属性:

    index={1}                     默认位置, 从0开始
    showsButtons={true}        是否显示按钮
    autoplayTimeout={2.5}          自动播放停留时间
    autoplay={true}               是否自动播放
    showsPagination={true}         显示分页指示器

网络请求(fetch) *

  • Axios
  • fetch
  • componentDidMount执行请求并在回调中执行setState

    // 组件已经挂载
    componentDidMount() {
        const url = 'http://api.douban.com/v2/movie/in_theaters';
        fetch(url).then(res => res.json())
            .then(data => {
            // 处理网络json数据
            this.setState({
                isLoading: false,
                movieList: data.subjects
            })
            // console.warn(data.subjects)
        }).catch((err) => {
            console.error(err);
        });
    }

长列表(FlatList) *

  • 长列表优化

    <FlatList
        data={this.state.movieList}
        keyExtractor={(item, index) => item.id}
        renderItem={({ item, index }) => {
            return (
                <View style={{ padding: 10, flexDirection: 'row' }}>
                    <Text>{item.title}: {item.year} : {index} </Text>
                </View>
            )
        }}
     />
  • 加载指示器

    <View style={{ flex: 1, padding: 20 }}>
        <ActivityIndicator />
    </View>
  • 条目点击跳转

Actions.movieDetail({ "movieId": movie.id, "movieTitle": movie.title});

滚动视图(ScrollView)

  • 发送网络请求
  • 渲染视图

日志与调试

  • 查看RN日志:

    react-native log-ios
    react-native log-android

    android也可在PC控制台输入

    adb logcat *:S ReactNative:V ReactNativeJS:V

  • 应用内的错误与警告

    console.warn('Yellow.');
    console.error('Red.');
  • Debug调试

    • Chrome开发者工具
    1. 在Android设备菜单中选择“Debug JS Remotely”,PC会自动通过Chrome浏览器打开调试页面 http://localhost:8081/debugger-ui (需要自行安装Chrome)。这里注意自动打开的主机地址可能不是localhost,需要手动改成localhost (不修改,则手机页面可能是空白)

    2. 在Chrome浏览器按Ctrl + Shift + IF12打开控制台

    3. 选中Sources选项卡 -> Network标签 -> debuggerWorker.js 打开指定组件文件即可

    4. 如果没有没有debuggerWorker.js, 查看页面最下边的Status提示。

      Status: Another debugger is already connected

      另一个调试器已连接,直接使用或关闭那个调试器

      Status: Waiting, press Ctrl R in simulator to reload and connect.

      等待中,建议重新加载模拟器

    5. 可以在代码中打断点,Console中执行js代码打印变量、执行脚本

    6. 关闭调试:在Android设备菜单中选择“Stop Remote JS Debugging”即可

打包及发布

  • 参见中文官网文档:https://reactnative.cn/docs/0.51/signed-apk-android.html#content

  • 多端统一开发框架:https://github.com/NervJS/taro 生成能运行在微信小程序、H5、React Native 等的应用
  • 修改图标
    • [项目名称]\android\app\src\main\res\mipmap-xhdpi

今天所有安装的包

  1. react-native-router-flux 路由

    应用场景:在RN项目中进行路由跳转时使用

    安装方式:yarn add react-native-router-flux

  2. react-native-swiper 开源轮播图

    应用场景:在首页展示轮播图

    安装方式:yarn add react-native-swiper

猜你喜欢

转载自www.cnblogs.com/xiaocongcong888/p/9436192.html