React Native学习笔记之–组件之间数据的传递和跳转
- 自定义属性的定义方式和传递
假定组件ComponentA中的自定义属性为
static props = {
title: '',
data: ''
}
数据的传递(这样在ComponentA便能接收到传递的数据了)
<ComponentA title='标题' data="数据"></ComponentA>
- 利用Navigator传递数据(向组件DetailView传递数据,然后在DetailView的props中获取message的数据)
this.props.navigator.push({
component: DetailView,
passProps: {'message' : '利用导航传递数据'}
});
- 组件通过回调函数传递数据(类似原生开发的代理模式)
现在有一个需求,组件B中在主页中,现在需要点击组件B中的按钮,通过Navigator跳转到下一个页面中,并且携带数据。现在组件B中是拿不到this.props.navigator的,下面就通过回调的方式来处理这种需求。
解决方案:
1.在组件B中定义一个属性clickButtonCallback
2.点击组件B的按钮,判断clickButtonCallback是否实现,若实现,则调用
3.在主页中实现clickButtonCallback具体逻辑,跳转页面并传递参数
代码如下:
组件B
export default class ComponentB extends Component {
static props = {
clickButtonCallback: null,
}
render() {
return (
<View style={styles.container}>
<Text>组件B</Text>
<TouchableOpacity activeOpacity={0.5}
style={{backgroundColor: 'yellow'}}
onPress={() => {this.clickButton()}}
>
<Text>按钮:进入下一个页面</Text>
</TouchableOpacity>
</View>
);
}
clickButton() {
if (this.props.clickButtonCallback == null) return;
this.props.clickButtonCallback('传递的数据');
}
}
const styles = StyleSheet.create({
container: {
height: 160,
justifyContent: 'center',
backgroundColor: 'green',
alignItems: 'center'
},
});
主页中的代码:
export default class HomeView extends Component {
render() {
return (
<View style={styles.container}>
<View style={{backgroundColor: '#e8e8e8', height: 64, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{marginTop: 20}}>主页</Text>
</View>
<ComponentB clickButtonCallback={(data) => {this.clickComponentBMiddleButton(data)}}></ComponentB>
</View>
);
}
clickComponentBMiddleButton(data) {
this.props.navigator.push({
component: DetailView,
passProps: {'message' : data}
});
}
}
效果如下: