ReactNative学习总结(二)

最近学RN也大概有两个礼拜了。紧跟上篇总结ReactNative一些基础知识再总结下学习RN的笔记。

前言

学习RN,最好的学习办法就是看官方文档,里面有很详细的资料。

环境搭建

开发RN,Atom+Nuclide还是不错的选择。

Atom下载地址
安装Nuclide

$ git clone https://github.com/facebook/nuclide.git
$ cd nuclide
$ npm install     # 安装包依赖
$ apm link

安装好后,就可以进入项目的根目录执行命令

react-native run-ios
//or
react-native run-ios --simulator "iPhone 5s"
//or
react-native run-android

常用的一些细节

  • 回退一个页面
const backAction = NavigationActions.back();
this.props.navigation.dispatch(backAction);
//or
this.props.navigation.pop()
  • ref的使用
    组件之间的通信,可以通过ref的使用来进行通信
<FlatList
  ref={(refs) => {
     this.refreshListView = refs;
  }}
/>
  • DeviceEventEmitter使用

DeviceEventEmitter类似Android里面的EventBus,可以进行广播式通信

使用方式为:
接收广播的界面:

import  {DeviceEventEmitter} from 'react-native';
//...
componentDidMount() {
        this.subscription = DeviceEventEmitter.addListener('Key', this.refreshData.bind(this))
    };
    refreshData(data) {
        this.setState({
            data: data,
        });
    };
    componentWillUnmount() {
        if(this.subscription)
        this.subscription.remove();
    };

发送广播的界面:

import  {DeviceEventEmitter} from 'react-native';
//...
()=>{
     DeviceEventEmitter.emit('Key', {avatar:''})//第二个参数为传递的参数
}
  • 关于使用RN加载图片,部门图片显示不出来问题

RN自带的Image组件是没有缓存的,所以如果在Android的一些内存小的手机上,内存溢出之后就会出现图片显示不出来的问题,可使用react-native-fast-image,使用原生的框架加载图片

如遇到下面这个问题

Native Component component for xxx does not exist

可以尝试在项目的根目录执行下面的命令

react-native link react-native-fast-image
cd android & gradlew clean
cd .. and react-native run-ios/android
  • 上传图片
formData = new FormData();
for(var key in params){//上传文件携带的参数
    formData.append(key,params[key]);
}
for(var index in imgAry){//上传的文件
    let file = {uri: imgAry[index], type: 'multipart/form-data', name: 'image.jpg'};
    formData.append("files",file);
}       
  • moment的使用

主要是一些日期转换的使用,具体使用文档参考moment文档或者参考这篇博客

  • 上拉下拉封装框架

react-native-refresh-list-view

  • TabNavigation的使用

首先TabRouteConfigs

import React from 'react';
import LoveList from "../mine/LoveList";
import FollowList from "../mine/FollowList";

const TabFollowConfigs = {
  LoveList: {
      screen: LoveList,
      navigationOptions:({navigation}) => ({
          tabBarLabel:'最爱',
      }),
  },
  FollowList: {
      screen: FollowList,
      navigationOptions: ({navigation}) => ({
          tabBarLabel: '关注',
      }),
  },
};
module.exports = TabFollowConfigs

然后

const TabNavigatorConfigs = {
    initialRouteName: 'LoveList',
    tabBarComponent: TabBarTop,
    tabBarPosition: 'top',
    swipeEnabled: true,
    lazy: true,
    tabBarOptions: {
      activeTintColor:color.theme,
      inactiveTintColor:'grey',
      scrollEnabled: true,
      indicatorStyle:{
        backgroundColor:color.theme
      },
      style: {
        backgroundColor: 'white'
      },
      tabStyle: {width: tabWidth },
      labelStyle:{
        fontSize:14,
        marginLeft:0,
        marginRight:0
      }
    }
};

如果需要滚动,需要设置tabStyle的tabWidth,否则没有滚动的效果。

最后

const Tab = TabNavigator(TabRouteConfigs, TabNavigatorConfigs);
type props = {}

export default class Article extends Component<props>{
  constructor(props){
    super(props);
  }
  render(){
    return (
      <Tab screenProps={{navigation:this.props.navigation}}/>
    );
  }
}
  • Modal的使用

主要是弹出框的一些布局

<Modal
           animateionType={'fade'}
           transparent={true}
           onrequestclose={() => {console.log("Modal has been closed.")}}
           visible={this.state.modalVisible}
           supportedOrientations={['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right']}
           onOrientationChange={() => {console.log("Modal has been OrientationChange.")}}>
           <View style={YsListStyle.dialog}>
            //弹出框的一些布局
           </View>
        </Modal>

ART绘制

react-native-art-绘图入门

react-native-art-绘图入门Github

绘制扇形react-art

npm install i react-native-art --save

Surface

  • width : 渲染区域的宽
  • height : 定义渲染区域的高 Shape
  • d : 定义绘制路径
  • stroke : 描边颜色
  • strokeWidth : 描边宽度
  • strokeDash : 定义虚线
  • fill : 填充颜色 Text
  • funt : 字体样式,定义字体、大小、是否加粗 如: bold 35px Heiti SC Path
  • moveTo(x,y) : 移动到坐标(x,y)
  • lineTo(x,y) : 连线到(x,y)
  • arc() : 绘制弧线
  • close() : 封闭空间

mobx的使用

它主要是一个全局状态管理库,主要由Actions,State,Computed Values,Reactions组成。这里举个例子

UserStore.js

import { observable,computed,action } from 'mobx';
import { AsyncStorage } from 'react-native';
import AsyncStorageUtils from '../../utils/AsyncStorageUtils';

export default class UserStore {
    @observable
    userId;
    @observable
    token;
    constructor(){
      AsyncStorageUtils.getItem('user',(value)=>{
        this.updateUser(Json.parse(value));
      });
    }
    @action
    updateUser(user){
      this.userId = user.userId;
      this.token = user.token;
    }

    @computed get isLogin(){
      return (this.userId > 0 && typeof(this.token) != 'undefined'&& this.token != undefined && this.token != '')
    }

}

创建RooterStore.js

import { observable,computed,action } from 'mobx';
import UserStore from './UserStore';

class RootStore {
   constructor(){
     this.userStore = new UserStore();
   }
}

module.exports = new RootStore()

全局注入

//mobx
import { Provider } from 'mobx-react';
import RootStore from './src/mobx/store/RootStore';

const Navigator = StackNavigator({....

const BasicApp = () => {
    return (
      <Provider rootStore={RootStore}>
        <Navigator/>
      </Provider>

    );
}
AppRegistry.registerComponent('MyApplication', () => BasicApp);

然后使用

import {inject, observer} from 'mobx-react';

type props = {} ;
@inject('rootStore')
@observer
export default class Login extends Component<props>{

    changeUser(){
    this.props.rootStore.userStore.updateUser({
        'userId':Math.random()*15,
        'token':''
    });
  }
}

这样就创建完成了。

动画

  • 两个互补动画系统

全局的布局动画LayoutAnimation
精细的交互控制的动画Animated

关于Animated

支持四个可以动画化的组件:View,Text,ImageScrollView,也可以通过Animated.createAnimatedComponent()来封装你自己的组件

第一个动画,透明度动画Animated.timing的使用

import React,{ Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  Easing
} from 'react-native';

type props = {}

class FadeInView extends Component{
  constructor(props){
    super(props);
    this.state = {
      fadeInOpacity:new Animated.Value(0)
    }
  }
  componentDidMount(){
    Animated.timing(this.state.fadeInOpacity,{
        toValue:1,//目标值
        duration:2500,//动画时间
        easing:Easing.linear//缓动函数
    }).start();

  }
  render(){
    return (
      <Animated.View style={{...this.props.style,opacity:this.state.fadeInOpacity}}>
          {this.props.children}
      </Animated.View>
    );
  }
}

export default class Home extends Component<props>{
  constructor(props){
    super(props);

  }
  render(){
    return (
      <View style={styles.container}>
        <FadeInView style={{width: 250, height: 50, backgroundColor: 'powderblue'}}>
          <Text style={{fontSize: 28, textAlign: 'center', margin: 10}}>Fading in</Text>
        </FadeInView>
      </View>
    );
  }
}

Animated.parallel的使用(同时执行动画)

import React,{ Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  Easing
} from 'react-native';

type props = {}

class FadeInView extends Component{
  constructor(props){
    super(props);
    this.state = {
      fadeInOpacity:new Animated.Value(0),
      rotation:new Animated.Value(0)
    }
  }
  componentDidMount(){
    var timing = Animated.timing;
    Animated.parallel(['fadeInOpacity','rotation'].map(property => {
      return timing(this.state[property],{
        toValue:1,
        duration:3000,
        easing:Easing.linear
      })
    })).start();
  }
  render(){
    return (
      <Animated.View style={{...this.props.style,opacity:this.state.fadeInOpacity,
        transform:[{
          rotateZ:this.state.rotation.interpolate({
            inputRange:[0,1],
            outputRange:['0deg','360deg']
          })
        }]
      }}>
          {this.props.children}
      </Animated.View>
    );
  }
}

export default class Home extends Component<props>{
  constructor(props){
    super(props);

  }
  render(){
    return (
      <View style={styles.container}>
        <FadeInView style={{width: 250, height: 50, backgroundColor: 'powderblue'}}>
          <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
            <Text style={{textAlign: 'center',alignSelf:'center',fontSize:26}}>Fading in</Text>
          </View>
        </FadeInView>
      </View>
    );
  }
}

interpolate主要是数组之间的转换

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,367评论 6 512
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,959评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,750评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,226评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,252评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,975评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,592评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,497评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,027评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,147评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,274评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,953评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,623评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,143评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,260评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,607评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,271评论 2 358

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,225评论 25 707
  • 上一篇日志还是在一年前的冬天,如今转眼又是一年,去年的圣诞还在宿舍里看着那些纸条泪流满面,今年虽然买了两张电影票,...
    一个人的太阳_阅读 386评论 0 2
  • 脸部的皮肤尤其领令人关注,因为人的形象都是从脸上反应的。一个人长的好不好看,脸就是最直观的体现。所以人们都在乎自己...
    点后ifeof阅读 1,363评论 1 0
  • 房子终于算是告一段落。 搬家大概断断续续花费一个月时间。请搬家公司挪了几个大件。另外细碎的物品自己开车一趟趟运,很...
    南言阅读 316评论 0 0
  • 你说会给我带来幸福,快乐。 可是你却不知我的幸福,我的快乐是什么? 你说会努力工作,赚很多钱,住大房子,到处旅游。...
    思彤lu阅读 243评论 4 2