Skip to content

react-native初体验(2) — 认识路由 #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
some-code opened this issue Jun 7, 2018 · 0 comments
Open

react-native初体验(2) — 认识路由 #10

some-code opened this issue Jun 7, 2018 · 0 comments
Labels

Comments

@some-code
Copy link
Owner

如果学习止步于 hello world, 那么人生也太没意思了。这次要做一个看起来真实的应用。多添加几个页面,让他们可以交互,动起来。

react-native 官方推荐使用 react-navigation 作路由管理,下面我将尝试使用他。

根目录下面建立 pages 文件夹,并在里面建立 home.js/user/index.js 两个文件,接下来就可以在这个两个视图之间进行跳转了

mkdir pages
cd pages
touch home.js
mkdir user
cd user
touch index.js

安装路由管理

安装

yarn add react-navigation

引入

// app.js
import { createStackNavigator } from 'react-navigation';

建立路由导航

修改 app.js, 使用 createStackNavigator 创建堆栈卡片式的导航。

import { createStackNavigator } from 'react-navigation';
import Home from './pages/home.js';
import Profile from './pages/user/index.js';

const App = createStackNavigator({
  Home: { screen: Home },
  Profile: { screen: Profile },
});

export default App

这里建立了两个视图的导航, yarn ios 试一下,报错了,原因是新建的2个视图面还是空的,没有返回一个 react compontent。现在关掉服务,在里面写2个组件。

多个页面

在两个页面里面随便写一些东西,navigationOptions 是路由的配置项,设置后会自动在视图顶部生成一个原生的导航组件。

  • home.js
// home.js
import ...;

export default class Home extends React.Component {
  static navigationOptions = {
    title: '首页',
  };
  render() {
    return (...);
  }
}

const styles = StyleSheet.create(...);
  • user/index.js
// user/index.js
import ...;

export default class Home extends React.Component {
  static navigationOptions = {
    title: '个人中心',
  };
  render() {
    return (...);
  }
}

const styles = StyleSheet.create(...);

跳转和返回

从一个页面跳转到另一个页面,需要调用 navigate 方法, 点击 Button, 会在当前视图上叠加 Profile 视图。点击 Profile 上边的返回按钮,会自动返回到 Home 视图。

// home.js
import ...;

export default class Home extends React.Component {
  static navigationOptions = {
    title: '首页',
  };
  render() {
  const { navigate } = this.props.navigation;
  return (
    <Button
        title="去个人中心"
        onPress={() =>
          navigate('Profile', { name: 'Jane' })
        }
     />
    );
  }
}

const styles = StyleSheet.create(...);
@some-code some-code added the react label Jun 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant