上一篇文章练习了Rn中使用Navigator跳转页面。我们一个完成的应用中一般不仅仅是跳转页面,经常还会传一些参数到下一个界面。Rn中怎么实现传参呢?
例子代码:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
Image,
Navigator
} from 'react-native';
class RnWidget extends Component {
render() {
let defaultName = 'firstPageName';
let defaultComponent = FirstPageComponent;
return (
{
return Navigator.SceneConfigs.FloatFromRight
}
}
renderScene = {(route,navigator)=>{
let Component = route.component;
return
}}
/>
)
}
}
//第一个界面
class FirstPageComponent extends Component{
constructor(props){
super(props);
this.state={
title :"title哈哈"
}
}
clickJump(){
//因为Navigator 传入了navigator 所以这里能取到navigator
const{navigator} = this.props;
let that = this;
if(navigator){
navigator.push({
name : "SecondPageComponent",
component : SecondPageComponent,
params :{
title:this.state.title,
id:123,
getUser:function(user){
that.setState({
user:user
})
}
}
})
}
}
render(){
return(
我是第一个界面
"rgb(181, 136, 254)"
activeOpacity={0.5}
style={{ borderRadius: 8,padding: 8,marginTop:5,backgroundColor:"#0588fe"}}
onPress={this.clickJump.bind(this)}
>
点击进入第二个界面
第二个界面返回:{this.state.user}
)
}
}
//第二个界面
class SecondPageComponent extends Component{
constructor(props){
super(props);
this.state={
id:null
}
}
clickJump(){
if(this.props.getUser){
this.props.getUser("大海")
}
const{navigator} = this.props;
if(navigator){
//把当前页面pop掉 回到上一个页面
navigator.pop();
}
}
componentDidMount(){
this.setState({
title:this.props.title,
id:this.props.id
})
}
render(){
return(
我是第二个界面
"rgb(181, 136, 254)"
activeOpacity={0.5}
style={{ borderRadius: 8,padding: 8,marginTop:5,backgroundColor:"#0588fe"}}
onPress={this.clickJump.bind(this)}
>
点击返回第一个界面
第一个界面传入:{this.state.title}
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ffffff',
},
});
AppRegistry.registerComponent('RnWidget', () => RnWidget);
navigator.push({
name : "SecondPageComponent",
component : SecondPageComponent,
params :{
title:this.state.title,
}
})
第二个界面在生命周期函数componentDidMount()中给state赋值。componentDidMount是当render()完成的时候调用
componentDidMount(){
this.setState({
title:this.props.title,
})
}
params :{
title:this.state.title,
id:123,
getUser:function(user){
that.setState({
user:user
})
}
}
第二个页面在navigator.pop();之前调用第一个界面传过来的getUser方法。
if(this.props.getUser){
this.props.getUser("大海")
}