能跳轉以后,不可避免的就要涉及到傳值的問題,下面也來記錄下正向傳值
首先,我們需要對Navigator的renderScene進行設置
//渲染
renderScene(route, navigator) {
//導航條跳轉傳遞參數 params 為傳遞的參數 其他頁面傳值時的名字要和這里設置的一樣
return <route.component {...route.params} navigator={navigator}/>
//沒有參數
// return <route.component navigator={navigator} />
}
然后,在頁面跳轉的方法里面這樣寫
//params對應的就是我們要傳的值,這里我傳了兩個值
goPage2() {
this.props.navigator.push({
component:SecondPageComponent,
params:{//params 要和HomePage.js里面的 renderScene(route, navigator)里面設置的參數名一樣
param1:'第一個參數',
param2:'第二個參數',
}
})
}
再然后,我們需要在第二個頁面接收這兩個值,所以我們要聲明兩個屬性進行接收
constructor(props){
super(props);
//這兩個屬性就是我們要接收第一頁傳過來的兩個值
this.state = {
paramGet1:PropTypes.string,
paramGet2:PropTypes.string,
};
}
再再然后,屬性已經聲明了,下面就是接收值了
//這個方法就是聲明周期的其中一個了,render()運行后,就會調用這個方法,我們在這里接收傳過來的兩個值
componentDidMount() {
//這里獲取從FirstPageComponent傳遞過來的參數
this.setState({
paramGet1: this.props.param1,
paramGet2: this.props.param2,
});
}
接收過來的值顯示到頁面上
render() {
return (
<View style={firstPageStyle.viewStyleBase}>
<TouchableOpacity onPress={() => this.backPage1()}>
<Text style={firstPageStyle.textStyleBase}>第二頁</Text>
</TouchableOpacity>
<Text style={{backgroundColor:'red'}}>參數1:{this.state.paramGet1}</Text>
<Text style={{backgroundColor:'red'}}>參數2:{this.state.paramGet2}</Text>
</View>
)
}
OK,這樣就可以正向傳值了
navgif.gif