今天我们来说一说RN的组件之间的通信。
ReactNative的核心之一是他的组件化,组件化的核心是组件之间的通信。
组件是有层级来区分的,譬如:父组件 子组件。
我们先来讲解一个例子。
这个是我们要实现的功能,是一个表单的一部分,首先我们想到的是抽象组件。
组件有2种状态
组件的代码如下:
import React, { Component } from 'react'; var { StyleSheet, View, Text, Image, TextInput, PixelRatio, TouchableHighlight, Dimensions, TextInput, TouchableWithoutFeedback, TouchableOpacity, } = require('react-native') const {screenWidth, screenHeight} = Dimensions.get('window'); const PxRatio = 2; export default class CourseType extends Component{ constructor(props) { super(props); this.state={ choosed : this.props.choosed, } } modifyChoosed(choosed){ this.setState({choosed : choosed}); } render() { return ( <View style={styles.row}> <TouchableOpacity style={styles.imageView} onPress={this.props.onPress} > <Image source={this.state.choosed == 0 ?require('image!unselected') :require('image!red_selected') } /> </TouchableOpacity> <View style={styles.textInputTitle}> <Text style={styles.textTitle}> {this.props.title} </Text> </View> <Text style={{flex:1}}/> { this.state.choosed == 0 ? null : <TextInput style={styles.ksValueView} maxLength={5} placeholder="0" placeholderTextColor="#b2b2b2" multiline={false} onChangeText={()=>{}} keyboardType="numeric" /> } { this.state.choosed == 0 ? null : <View style={styles.ksTipView} > <Text style={styles.ksTipText}>元/课时</Text> </View> } </View> ); } } const styles = StyleSheet.create({ row: { backgroundColor: '#ffffff', flexDirection: 'row', height: 90 / PxRatio, alignItems: 'center', width:screenWidth, }, imageView: { marginLeft: 30/PxRatio, }, textInputTitle: { marginLeft:20/PxRatio, alignItems:'center', }, textTitle:{ fontSize: 28/PxRatio, color:'#666666', }, ksValueView:{ width:128/PxRatio, height:52/PxRatio, alignSelf:'center', borderWidth: 1/PxRatio, borderColor:'#dbdbdb', textAlign:'center' }, ksTipView:{ marginRight:30/PxRatio, marginLeft:20/PxRatio, }, ksTipText:{ fontSize: 28/PxRatio, color:'#333333', }, });
提供了一个onPress方法,控制选中状态的切换。其中这个方法是由props传递过来的。
定义了modifyChoosed方法来修改状态机变量choosed
好,组件封装完毕,那在表单页面我们怎么来使用这个组件呢。
1、import组件模块
import CourseType from './CourseType';
2、使用组件
<CourseType ref="stu" title="学生上门" choosed={this.state.type_stu} onPress={()=>{ let choosed = this.state.type_stu == 0 ? 1:0; this.refs.stu.modifyChoosed(choosed); this.setState({type_stu:choosed}) }} />
好了,这样我们就实现了功能。
那我们总结下,这个是重点。
表单相当于父组件,CourseType相当于子组件。
子组件可以通过this.props 调用父组件的方法。
那父组件如何调用子组件的方法呢?
首先在子组件上定义一个ref=xxx,然后在父组件内通过this.refs.xxx.子组件Method()来调用。