Quick Start | 快速开始

如果这是你首次开发 React Native 应用,我们推荐你阅读 facebook 的官方指南:“Getting Started”

Installation | 安装

React Router Native 已经 发布到 npm 因此你可以使用 npm 或者 yarn

  1. npm install react-router-native
  2. # 或
  3. yarn add react-router-native

当你创建完 React Native 项目后,你可以复制任意的示例代码,并粘贴到 index.ios.jsindex.android.js

代码如下:

  1. import React from 'react'
  2. import {
  3. StyleSheet,
  4. Text,
  5. View,
  6. AppRegistry,
  7. } from 'react-native'
  8. import { NativeRouter, Route, Link } from 'react-router-native'
  9. const Home = () => (
  10. <Text style={styles.header}>
  11. 首页
  12. </Text>
  13. )
  14. const About = () => (
  15. <Text style={styles.header}>
  16. 关于
  17. </Text>
  18. )
  19. const Topic = ({ match }) => (
  20. <Text style={styles.topic}>
  21. {match.params.topicId}
  22. </Text>
  23. )
  24. const Topics = ({ match }) => (
  25. <View>
  26. <Text style={styles.header}>主题列表</Text>
  27. <View>
  28. <Link
  29. to={`${match.url}/rendering`}
  30. style={styles.subNavItem}
  31. underlayColor='#f0f4f7'>
  32. <Text>Rendering with React</Text>
  33. </Link>
  34. <Link
  35. to={`${match.url}/components`}
  36. style={styles.subNavItem}
  37. underlayColor='#f0f4f7'>
  38. <Text>Components</Text>
  39. </Link>
  40. <Link
  41. to={`${match.url}/props-v-state`}
  42. style={styles.subNavItem}
  43. underlayColor='#f0f4f7'>
  44. <Text>Props v. State</Text>
  45. </Link>
  46. </View>
  47. <Route path={`${match.url}/:topicId`} component={Topic}/>
  48. <Route exact path={match.url} render={() => (
  49. <Text style={styles.topic}>选择一个主题。</Text>
  50. )} />
  51. </View>
  52. )
  53. const nativeRouterExamples = () => (
  54. <NativeRouter>
  55. <View style={styles.container}>
  56. <View style={styles.nav}>
  57. <Link
  58. to="/"
  59. underlayColor='#f0f4f7'
  60. style={styles.navItem}>
  61. <Text>首页</Text>
  62. </Link>
  63. <Link
  64. to="/about"
  65. underlayColor='#f0f4f7'
  66. style={styles.navItem}>
  67. <Text>关于</Text>
  68. </Link>
  69. <Link
  70. to="/topics"
  71. underlayColor='#f0f4f7'
  72. style={styles.navItem} >
  73. <Text>主题列表</Text>
  74. </Link>
  75. </View>
  76. <Route exact path="/" component={Home}/>
  77. <Route path="/about" component={About}/>
  78. <Route path="/topics" component={Topics}/>
  79. </View>
  80. </NativeRouter>
  81. )
  82. const styles = StyleSheet.create({
  83. container: {
  84. marginTop: 25,
  85. padding: 10,
  86. },
  87. header: {
  88. fontSize: 20,
  89. },
  90. nav: {
  91. flexDirection: 'row',
  92. justifyContent: 'space-around'
  93. },
  94. navItem: {
  95. flex: 1,
  96. alignItems: 'center',
  97. padding: 10,
  98. },
  99. subNavItem: {
  100. padding: 5,
  101. },
  102. topic: {
  103. textAlign: 'center',
  104. fontSize: 15,
  105. }
  106. })
  107. AppRegistry.registerComponent('MyApp', () => App);