美文网首页React Native开发经验集
React Native学习笔记(八)—— 父组件与子组件方法相

React Native学习笔记(八)—— 父组件与子组件方法相

作者: sml_tj | 来源:发表于2018-09-25 15:36 被阅读6次

在React native 开发中可以很方便的将通用的控件封装为子组件,本文主要介绍了父组件和子组件的交互,包含:
(1)父组件传递属性到子组件
(2)父组件调用子组件的方法
(3)子组件调用组件中的方法

我们使用一个小Demo来说明这个问题,Demo的界面如下:


image.png

子组件封装了一个FlatList,父组件中加载了子组件(图中灰色部分),父组件通过点击“调用子组件方法”按钮,调用子组件中的方法,修改列表中展示的内容,子组件选中列表中的某一项后,调用父组件的方法,展示到左上角的Text控件中

代码:
Parent.js

import React,{Component} from 'react'
import{
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
    SafeAreaView

}from 'react-native'

import Child from './Child'

export default class Parent extends Component{
    constructor(props){
        super(props)

        this.state={
            selectedText:'********'
        }
    }
    render(){
        return(
           <SafeAreaView
            style={styles.container}>

               <View style={{flexDirection:'row'}}>
                   <Text style={styles.text}>
                       {this.state.selectedText}
                   </Text>

                   <TouchableOpacity style={styles.btn} onPress={()=>{
                       this.childList.changeListData()
                   }}>
                       <Text>调用子组件的方法</Text>
                   </TouchableOpacity>
               </View>


               <Child  ref={(view)=>this.childList=view} listData={['早','中','晚']} _itemSelect={(item)=>{
                   this._showItemText(item)
               }}/>





           </SafeAreaView>
        )
    }

    _showItemText(item){
        console.log('((((((('+item)
        this.setState({
            selectedText:item
        })
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        alignItems:'center',
        justifyContent:'center'
    },
    text:{
        margin:80,
        marginTop:100,
        backgroundColor:'pink',
    },
    btn:{
        margin:80,
        marginTop:100,
        padding:10,
        backgroundColor:'red'
    }
})

Child.js

import React,{Component} from 'react'
import {
    View,
    FlatList,
    TouchableOpacity,
    StyleSheet,
    Text
}from 'react-native'

import PropTypes from 'prop-types'


export default class Child extends Component{

    constructor(props){
        super(props)

        this.state={
            listData:this.props.listData
        }
    }

    render(){
        return(
            <View>
                <FlatList data={this.state.listData}
                          renderItem={this._renderItem}
                          style={styles.flatList}
                          keyExtractor={(item, index) => 'time' + index}
                          getItemLayout={(data, index) => ({
                              length:40, offset: 40 * index, index
                          })}
                />
            </View>
        )
    }


    _renderItem=({item,index})=>{
        return(
            <TouchableOpacity style={styles.item}
                              onPress={()=>{ this.props._itemSelect(item)}}>
                <Text style={{fontSize:18, color: '#333333'}}>{item}</Text>
            </TouchableOpacity>
        )
    }

    changeListData(){
        this.setState({
            listData:['起床','工作','睡觉']
        })
    }
}



Child.propTypes = {
    _itemSelect:PropTypes.func,
    listData:PropTypes.array
};
Child.defaultProps = {
    _itemSelect:(index)=>{},
    listData:['早','中','晚']
};


const styles = StyleSheet.create({
    flatList:{
        backgroundColor:'#f0f0f0',
    },
    item:{
        paddingHorizontal:24,
        height: 40,
        justifyContent:'center'
    }
})
  1. 父组件传递属性到子组件
listData={['早','中','晚']} _itemSelect={(item)=>{
                   this._showItemText(item)

子组件可以设定属性的类型和默认值

Child.propTypes = {
    _itemSelect:PropTypes.func,
    listData:PropTypes.array
};
Child.defaultProps = {
    _itemSelect:(index)=>{},
    listData:['早','中','晚']
};

2.父组件调用子组件的方法
通过ref指向子组件,在需要的地方调用子组件中的方法。
ref是组件的一种特殊属性,可以理解为,组件被渲染后,指向组件的一个引用。我们可以通过ref属性来获取真实的组件。

ref={(view)=>this.childList=view}
 <TouchableOpacity style={styles.btn} onPress={()=>{
                       this.childList.changeListData()
                   }}>
                       <Text>调用子组件的方法</Text>
                   </TouchableOpacity>

3.子组件调用组件中的方法
父组件将回调方法作为属性传递给子组件,子组件在需要的地方调用

listData={['早','中','晚']} _itemSelect={(item)=>{
                   this._showItemText(item)
  <TouchableOpacity style={styles.item}
                              onPress={()=>{ this.props._itemSelect(item)}}>
                <Text style={{fontSize:18, color: '#333333'}}>{item}</Text>
            </TouchableOpacity>

相关文章

  • React Native学习笔记(八)—— 父组件与子组件方法相

    在React native 开发中可以很方便的将通用的控件封装为子组件,本文主要介绍了父组件和子组件的交互,包含:...

  • react中调用子组件的方法

    class组件 父组件 子组件 react hook 父组件调用子组件方法 父组件 子组件

  • React 父子组件通信

    通讯是单向的,数据必须是由一方传到另一方。 1.父组件与子组件间的通信。 在 React 中,父组件可以向子组件通...

  • react native 动画

    第三方组件:react-native-animatable react native组件:Animated

  • React父子组件间通信的实现方式

    React学习笔记之父子组件间通信的实现:今天弄清楚了父子组件间通信是怎么实现的。父组件向子组件通信是通过向子组件...

  • react组件传值的几种方式

    react 组件传值一、父组件传给子组件父组件通过props传递给子组件; 二、子组件传给父组件父组件通过prop...

  • vue、react对比

    一、父子通信 1. 父组件通过props向子组件传值 vue:父组件 子组件接收 react:父组件: 子组件: ...

  • react学习笔记

    React笔记 创建项目 入口文件 组件构成 子组件对父组件的校验等 React的虚拟Dom实现原理 state数...

  • React父子组件之间如何通信?

    父组件向子组件通讯 通讯是单向的,数据必须是由一方传到另一方。在 React 中,父组件可以向子组件通过传 pro...

  • react子组件向父组件传值

    相关资料:react 父组件怎么获取子组件的这个值React组件间信息传递方式react同级组件之间传值 • 父...

网友评论

    本文标题:React Native学习笔记(八)—— 父组件与子组件方法相

    本文链接:https://www.haomeiwen.com/subject/ipkloftx.html