react - 3.页面变量的渲染和传递参数

访问量: 331

普通变量的渲染

  render(){
    const message = "明日ReactNative 大神就要诞生了!"
    return (
      <View>
        <Text>
          {message}
        </Text>
      </View>
   )
  }

跳转页面时,传递参数

参考:https://reactnavigation.org/docs/en/params.html

1. 修改Home.js文件,用来产生跳转

        // 在  Home.js 文件中, 增加该代码: 
        <Button title = "传递参数到新页面: (打个招呼) "
          onPress = {
            () => this.props.navigation.navigate("SayHi", { name: 'Siwei'})
          }
        />

2. 为这个 "SayHi" 页面创建文件:( ./screens/SayHi.js) 

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

export default class AboutUs extends React.Component{

  render(){
    const name = this.props.navigation.getParam('name', "Lily")
    return (
      <View>
        <Text>
        你好啊, {name }
        </Text>
      </View>
    )
  }

}

3. 添加对应的路由: (修改App.js)

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, Alert} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';

import Home from 'screens/Home'
import AboutUs from 'screens/AboutUs'
// 新引入该文件
import SayHi from 'screens/SayHi'

const myNavigator = createStackNavigator(
  {
    Home: Home,
    AboutUs: AboutUs,
    // 在路由中做标记, 不加这一行的话,页面不会跳转。 
    SayHi: SayHi
  },
  {
    initialRouteName: "Home"
  }
)

export default createAppContainer(myNavigator)

这样, 点击Home页的按钮,就可以看到效果了 , 页面显示 hello siwei

订阅/RSS Feed

Subscribe

分类/category