可以说,组件间通信是react native开发的基础中的基础,但凡具有一定规模的项目,都一定会涉及组件间通信。
组件间通信大体有下面几种情况:
- 父组件向子组件通信
- 子组件向父组件通信
下面依次说下这几种通信方式。
一、父组件向子组件通信
父组件通过向子组件传递props,子组件得到props后进行相应的处理。
下面是演示代码:
父组件ParentComponent.js:
export default class ParentComponent extends Component {
render() {
return (//调用子组件,并向子组件传值
<View style={styles.container}>
<ChildComponent
childData="父组件传给子组件的值"/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 20,
marginTop: 10,
backgroundColor: '#666',
alignItems: 'center'
}
});
子组件ChildComponent.js:
export default class ChildComponent extends Component {
render() {
const {childData} = this.props
return (
<TouchableOpacity style={styles.div}>
<Text>{childData}</Text>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
div: {
width: 50,
height: 50,
backgroundColor: '#f00',
justifyContent: 'center',
alignItems: 'center'
}
});
二、子组件向父组件通信
利用回调函数,可以实现子组件向父组件通信:父组件定义好state和处理该state的函数,将该函数通过props传给子组件;子组件调用该父组件传进来的函数,来修改父组件的state值。
下面是演示代码:
ParentComponent.js:
export default class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
childData: ""
}
}
handleChild = (value) => {//定义回调,子组件向父组件传值
this.setState({
childData: value
})
}
render() {
const {childData} = this.state
return (//调用子组件,并向子组件传值
<View style={styles.container}>
<Text>{childData}</Text>
<ChildComponent
childData={childData}
handleChild={this.handleChild}/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 20,
marginTop: 10,
backgroundColor: '#666',
alignItems: 'center'
}
});
ChildComponent.js:
export default class ChildComponent extends Component {
getRandom = (start, end) => {
var length = end - start
var num = parseInt(Math.random() * length + start)
return num
};
render() {
const {childData, handleChild} = this.props
const value = this.getRandom(5, 97)
return (
<TouchableOpacity style={styles.div} onPress={handleChild.bind(this,value)}>
<Text>{childData}</Text>
<Text>点我</Text>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
div: {
width: 50,
height: 50,
backgroundColor: '#f00',
justifyContent: 'center',
alignItems: 'center'
}
});
三、总结
本文讲解了“父组件向子组件通信”和“子组件向父组件通信”,其实还有其他的组件间通信的场景,不过最终都可以转为这两种通信方式。如下两种方式
跨级通信
非嵌套组件通信
对于比较复杂的项目,这样实现组件间通信未免过于繁琐,所以引入了redux。具体可以参考《【React Native入门系列文章 十】如何从零开始学redux?》。
想要查看本文以及《React Native入门系列文章》的源码,可以下载demo:
demo地址(觉得ok,可以先star,会持续更新)