正向传值
A->B
1. A页面跳转B页面:
this.props.navigation.navigagte(routeName,params,actions);
//routeName:跳转路由页面名称(需要在RouteConfig中定义)。
//params:跳转携带的参数对象。
2. B页面获取A页面传递过来参数:
this.props.navigation.state.params.xxx;
//xxx为参数名(需与A页面中params内对应),如果没有值,则为null
this.props.navigation.getParam('xxx','abc');
//xxx为参数名, 如果没有值,则取abc 作为默认值
反向传值
A -> B -> A
//A页面跳转B,params中指定callback回调参数,用于接受B页面返回数据。
this.props.navigation.navigate('B', {
title:'跳转B页面',
passCallback: (data) => {
console.log('B回传的数据:' + data);
}
});
<TouchableOpacity onPress={()=> this.change2()}>
</TouchableOpacity>
change2 () {
if(this.props.navigation.state.params.passCallback) {
this.props.navigation.state.params.passCallback("12345");
}
};
同级数据交换
标题栏与其所属的页面之间的交互
1.通过生命周期控制
class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => <LogoTitle />,
headerRight: () => (
<Button
// 1. 同步调用
//onPress={navigation.getParam('increaseCount')}
//2. 异步调用
onPress={()=>{navigation.getParam('increaseCount')()}}
title="+1"
color="#fff"
/>
),
};
};
componentDidMount() {
this.props.navigation.setParams({ increaseCount: this._increaseCount });
}
state = {
count: 0,
};
_increaseCount = () => {
this.setState({ count: this.state.count + 1 });
};
/* later in the render function we display the count */
}
2.使用that辅助
class HomeScreen extends React.Component {
let
that;
constructor(props) {
super(props);
that = this;
};
static navigationOptions = ({navigation}) => {
const params = navigation.state.params || {};
return {
headerTitle:()=> <LogoTitle />,
headerLeft:()=> (
<Button onPress = {()=> navigation.navigate("MyModel2") }
title = "info"
color={Platform.OS === 'ios'?'#fff':null}></Button>
),
headerRight: ()=> {
return <Button onPress = {that._increaseCount} title="+1" color={Platform.OS === 'ios'?'#fff':null } />
}
}
};
state = {
count:0,
}
_increaseCount = ()=> (this.setState({count:this.state.count + 1}))
render() {
return (
<View style={{flex:1, alignItems:"center", justifyContent:"center"}}>
<Text>Home HomeScreen</Text>
<Text> count:{this.state.count}</Text>
<Button title="go to details "
onPress={ ()=> {
this.props.navigation.navigate('Details',{
itemID:86,
otherParam:"first details",
})
}} />
</View>
)
}
}
网友评论