初始化安装:
yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
yarn add @react-navigation/native @react-navigation/stack
配置
- 将下面内容添加到index.js 或者 App.js 开头,如果不添加在
import 'react-native-gesture-handler';
- Android 配置
更新MainActivity.java文件 添加下面代码
package com.swmansion.gesturehandler.react.example;
import com.facebook.react.ReactActivity;
+ import com.facebook.react.ReactActivityDelegate;
+ import com.facebook.react.ReactRootView;
+ import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
public class MainActivity extends ReactActivity {
@Override
protected String getMainComponentName() {
return "Example";
}
+ @Override
+ protected ReactActivityDelegate createReactActivityDelegate() {
+ return new ReactActivityDelegate(this, getMainComponentName()) {
+ @Override
+ protected ReactRootView createRootView() {
+ return new RNGestureHandlerEnabledRootView(MainActivity.this);
+ }
+ };
+ }
}
- 使用
避免每个组件都传navigation ={this.props.navigation}的繁琐,如下方法可以避免繁琐
获取navigation方法
1.利用hooks方法,在任何组件中不依赖任何组件
const navigation = useNavigation();
- 在根容器中添加一个ref
import { navigate, navRef } from '../utils/navService';
<NavigationContainer ref={navRef}>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Detail" component={DetailScreen} />
</Stack.Navigator>
</NavigationContainer>
- 创建一个ref
utils/navService.js
/**
* created by yue on 2020.12.08
* 封装导航
*
* 类型检查
* ? 表示可选
*/
import * as React from 'react';
export const navRef = React.createRef();
// 需要跳转的地方引入该FN即可
export function navigate(routeName, params) {
return navRef.current?.navigate(routeName, params);
}
export function goBack() {
return navRef.current?.goBack();
}
// todos 添加并导出更多想要的Nav操作
网友评论