react-navigation 源码简单分析以及徒手撸react-navigation简易版

目标简单做个导航效果的Navigator

在接触ReactNative中 渲染视图最重要即render方法去渲染,对于react-navigation如何缓存之前的视图对象,以及如何在一个容器里面做到跳转效果(Acitvity 的概念),以及回退了 之前对象还是缓存数据 有了兴趣,在阅读源码后简单模仿了低配版的Navigator

首先我们初始化项目后加入react-navigation

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

export default class PageA extends Component {
  static navigationOptions = {
    headerTitle: 'PageA'
  }
  constructor (props) {
    super(props)
    this.state = {
      number: 0
    }
  }
  render () {
    return (
      <View style={styles.container}>
        <Text>PageA</Text>
        <Button
          onPress={() => {
            this.setState({
              number: ++this.state.number
            })
          }}
          title={'计数器:'+this.state.number+''}
        />
        <Button
          onPress={() => {
            this.props.navigation.navigate('PageB')
          }}
          title='go to pageB'
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  }
})

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

export default class PageB extends Component{
  static navigationOptions = {
    headerTitle:'PageB',
  }; 
  render() {
    return (
      <View style={styles.container}>
        <Text>PageB</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

import {StackNavigator} from 'react-navigation';
//这里是我们之后要低配版导航
// import StackNavigator from './animatorCustomerNavigator/StackNavigator';
import PageA from './PageA'
import PageB from './PageB'
export default StackNavigator({
    PageA: {
        screen: PageA
    },
    PageB: { // 详情页
        screen: PageB
    },
},
{
    headerMode: 'screen',  // 标题导航
    initialRouteName: 'PageA', // 默认先加载的页面组件
    mode: 'card'       // 定义跳转风格(card、modal)
});
import React, { Component } from 'react'
import { Text } from 'react-native'
import Naviagtor from './src/Naviagtor'
import PageA from './src/PageA'
export default class App extends Component {
  render () {
    return <Naviagtor/>
  }
}

这个时候 以及跑起来项目了,首先我们先解决 react-navigation 如何做到组件的缓存
StackNavigator 为例 定位代码

StackNavigator=>
require('react-navigation-stack').createStackNavigator=>
require('./navigators/createContainedStackNavigator').default

在这里插入图片描述
调用navigateor 需要两个 stackView 和router,router是个控制器内部包含了视图栈的配置,控制,StackView就是一个容器根据router控制来显示view

createNavigator 源码 
   ....
   routes.forEach(route => {
        if (
          prevDescriptors &&
          prevDescriptors[route.key] &&
          route === prevDescriptors[route.key].state &&
          screenProps === prevState.screenProps
        ) {
          descriptors[route.key] = prevDescriptors[route.key];
          return;
        }
        const getComponent = router.getComponentForRouteName.bind(
          null,
          route.routeName
        );
        const childNavigation = navigation.getChildNavigation(route.key);
        const options = router.getScreenOptions(childNavigation, screenProps);
        descriptors[route.key] = {
          key: route.key,
          getComponent,
          options,
          state: route,
          navigation: childNavigation,
        };
      });

 return { descriptors, screenProps };

 render() {
      return (
       //这个NavigatorView 就是外部传进来的StackView
        <NavigatorView
          {...this.props}
          screenProps={this.state.screenProps}
          navigation={this.props.navigation}
          navigationConfig={navigationConfig}
          //这个就是router进行相应的具体配置如设置了key,getComponent,等
          descriptors={this.state.descriptors}
        />
      );
    }

StackRouter 大致就是定义了pop push actions等状态
接下来我们看StackView

  _render = (transitionProps, lastTransitionProps) => {
    const { screenProps, navigationConfig } = this.props;
    return <StackViewLayout {...navigationConfig} onGestureBegin={this.props.onGestureBegin} onGestureCanceled={this.props.onGestureCanceled} onGestureEnd={this.props.onGestureEnd} screenProps={screenProps} descriptors={this.props.descriptors} transitionProps={transitionProps} lastTransitionProps={lastTransitionProps} />;
  };

其实内部还是调用了StackViewLayout

StackViewLayout 中的render 方法
   render() {
        ....
         const {
      transitionProps: { scene, scenes }
    } = this.props;
    const { options } = scene.descriptor;
    ....
        return <View {...handlers} style={containerStyle}>
            <ScreenContainer style={styles.scenes}>
             //这里scenes map 实际上就是组建叠上去叠上去的
                {scenes.map(s => this._renderCard(s))}
            </ScreenContainer>
            {floatingHeader}
        </View>;
    }
我们追踪transitionProps
StackView transitionProps 实际上 Transitioner组建里面调用 的
  render() {
    return <Transitioner render={this._render} configureTransition={this._configureTransition} screenProps={this.props.screenProps} navigation={this.props.navigation} descriptors={this.props.descriptors} onTransitionStart={this.props.onTransitionStart || this.props.navigationConfig.onTransitionStart} onTransitionEnd={(transition, lastTransition) => {
      const { navigationConfig, navigation } = this.props;
      const onTransitionEnd = this.props.onTransitionEnd || navigationConfig.onTransitionEnd;
      if (transition.navigation.state.isTransitioning) {
        navigation.dispatch(StackActions.completeTransition({
          key: navigation.state.key
        }));
      }
      onTransitionEnd && onTransitionEnd(transition, lastTransition);
    }} />;
  }

Transitioner 源码

this._transitionProps = buildTransitionProps(props, this.state);

function buildTransitionProps(props, state) {
  const { navigation } = props;

  const { layout, position, progress, scenes } = state;
  
  const scene = scenes.find(isSceneActive);

  invariant(scene, 'Could not find active scene');

  return {
    layout,
    navigation,
    position,
    progress,
    scenes,
    scene,
    index: scene.index
  };
}

到这里我们也能看出栈的实现就是一个个组建叠上去的 同时浏览了Transitioner 源码大致也能猜出实际界面跳转就是一个组件动画实现的流程然后叠上去 在StackView 中有_configureTransition方法-》调用 StackViewTransitionConfigs.getTransitionConfig方法

//android 默认实现的动画配置,StackViewTransitionConfigs StackViewStyleInterpolator 这两个js中代码能找到
function defaultTransitionConfig(transitionProps, prevTransitionProps, isModal) {
  if (Platform.OS === 'android') {
    // Use the default Android animation no matter if the screen is a modal.
    // Android doesn't have full-screen modals like iOS does, it has dialogs.
    if (prevTransitionProps && transitionProps.index < prevTransitionProps.index) {
      // Navigating back to the previous screen
      return FadeOutToBottomAndroid;
    }
      return FadeInFromBottomAndroid;
  }
  // iOS and other platforms
  if (isModal) {
    return ModalSlideFromBottomIOS;
  }
  return SlideFromRightIOS;
}

简易版react-navigation 实现

import React, {Component} from 'react'
import {View, Dimensions, Text, Image, TouchableOpacity,DeviceEventEmitter} from 'react-native'
import createStackView from './StackView'

var width = Dimensions.get('window').width

var height = Dimensions.get('window').height
export default (createNavigationContainer = (routeConfigs, config = {}) => {
    class NavigationContainer extends React.Component {
        constructor(props) {
            super(props)
            const navigation = {
                navigate: name => {
                    this.state.stack.push({
                        config: routeConfigs[name].screen,
                        screen: createStackView(routeConfigs[name].screen, navigation, true,this.state.stack.length),
                        index: this.state.stack.length
                    })
                    this.forceUpdate()
                },
                pop: () => {
                    let str='pop'
                    str=str+String(this.state.stack.length-1)+''
                    DeviceEventEmitter.emit(str)
                    this.timer = setTimeout(
                        () => { this.state.stack.pop()
                            this.forceUpdate() },
                        500
                      );
                    
                }
            }
            this.state = {
                routeConfigs,
                config,
                stack: [{
                    config: routeConfigs[config.initialRouteName].screen,
                    screen: createStackView(routeConfigs[config.initialRouteName].screen, navigation, false,0),
                    index: 0
                }],
                navigation,
            }
        }

        render() {
            return (
                <View style={{flex: 1}}>
                    {this.state.stack.map((d) =>
                        <View style={{position: 'absolute', width, height}}>
                            {d.screen}
                        </View>)}
                </View>
            )
        }
        // render(){
        //     let Page = this.state.stack[this.state.stack.length - 1].screen
        //     return (
        //         <View style={{flex: 1}}>
        //             {Page}
        //         </View>
        //     )
        // }
    }

    return NavigationContainer
})

import React, { Component } from 'react'
import {
  View,
  Dimensions,
  Text,
  Image,
  TouchableOpacity,
  Animated,
  Easing,
  DeviceEventEmitter
} from 'react-native'
var width = Dimensions.get('window').width
var height = Dimensions.get('window').height
//考虑到缓存 就用方法去创建然后塞到数组里面
export default (createStackView = (Page, navigation, back,index) => {
  class StackView extends React.Component {
    constructor (props) {
      super(props)
      this.state = {
        active: false,
        opacity: new Animated.Value(0),
        transformX: new Animated.Value(0),
        transformY: new Animated.Value(0)
      }
      console.warn('pop'+index)
      this.subscription = DeviceEventEmitter.addListener('pop'+index,() =>{
        console.warn('fadoOutAnimator')
        this.fadoOutAnimator()
      })
    }

    componentWillUnmount() {
      // 移除
      this.subscription.remove();
  }
    componentDidMount () {
      Animated.parallel([
        Animated.timing(
          this.state.opacity, 
          {
            toValue: 1,
            duration: index==0?10:500,
            easing: Easing.in(Easing.poly(4)), 
            timing: Animated.timing
          }
        ),
        Animated.timing(this.state.transformY, {
          toValue: 1,
          duration: index==0?10:500,
          easing: Easing.in(Easing.poly(4)),
          timing: Animated.timing
        })
      ]).start(() => {})
    }
    fadoOutAnimator(){
      Animated.parallel([
        Animated.timing(
          this.state.opacity,
          {
            toValue: 0,
            duration: index==0?10:500,
            easing: Easing.in(Easing.poly(4)), 
            timing: Animated.timing
          }
        ),
        Animated.timing(this.state.transformY, {
          toValue: 0,
          duration: index==0?10:500,
          easing: Easing.in(Easing.poly(4)), // accelerate
          timing: Animated.timing 
        })
      ]).start(() => {})
    }
    render () {
      return (
        <Animated.View
          style={{
            flex: 1,
            opacity: this.state.opacity,
            transform: [
              {
                translateY: this.state.transformY.interpolate({
                  inputRange: [0, 1],
                  outputRange: [height, 0]
                })
              }
            ]
          }}
        >
          <View style={{ flex: 1 }}>
            <View
              style={{
                width,
                height: 50,
                backgroundColor: 'blue',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              {back &&
                <TouchableOpacity
                  onPress={() => {
                    navigation.pop()
                  }}
                  style={{ position: 'absolute', left: 10 }}
                >
                  <Image
                    source={require('./back-icon.png')}
                    style={{ tintColor: 'white' }}
                  />
                </TouchableOpacity>}
              <Text style={{ color: 'white' }}>
                {Page.navigationOptions.headerTitle}
              </Text>
            </View>
            <Page navigation={navigation} />
          </View>
        </Animated.View>
      )
    }
  }
  return <StackView />
})

福利图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值