使用Next JS和React Navigation响应本机Web

时间:2019-11-18 05:10:34

标签: reactjs react-native react-navigation next.js

我正在尝试确定在我的React Native Web项目中设置路由的最佳方法。我正在使用expo,并按照本指南使用Next JS https://docs.expo.io/versions/latest/guides/using-nextjs/,因此我拥有这样的App.js:

import index from "./pages/index";
import alternate from "./pages/alternate";
import { createStackNavigator } from "react-navigation-stack";
import { createAppContainer } from "react-navigation";
const AppNavigator = createStackNavigator(
  {
    index,
    alternate
  },
  {
    initialRouteName: "index"
  }
);

const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;

我关心的是如何最好地处理路由。我目前有这样的index.js页面设置。

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


export default function App ({navigation}) {
  return (
    <View style={styles.container}>

      {/* Native route */}
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate("alternate")}
      />

      {/* Web route */}
      <Text style={styles.link} accessibilityRole="link" href={`/alternate`}>
        A universal link
      </Text>
    </View>
  );
}

如您所见,当前需要使用单独的代码来呈现本机与Web路由。我想知道什么是处理这种渲染的最佳方法。我研究过使用React Navigation for web,并且不会反对,但似乎我应该坚持使用下一台路由器。

预先感谢您对处理这样的条件渲染的任何建议。

2 个答案:

答案 0 :(得分:1)

import { Platform } from 'react-native'

{Platform.OS === 'web' ? (
  <Text
    style={styles.link}
    accessibilityRole="link"
    href={`/alternate`}
  >
    A universal link
  </Text>
) : (
  <Button
    title="Go to Details"
    onPress={() => navigation.navigate("alternate")}
  />
)}

答案 1 :(得分:1)

为此使用reactnavigation网站支持

https://reactnavigation.org/docs/en/web-support.html

import { createSwitchNavigator } from "@react-navigation/core";
import { createBrowserApp } from "@react-navigation/web";

const MyNavigator = createSwitchNavigator(routes);

const App = createBrowserApp(MyNavigator);

// now you can render "App" normally