2020-12-22 ReactNative 父组件/子组件的调用方法

主要是刚用了onRef的使用,顺便记录一下,直接上代码吧~~

// 父组件

import React, {Component} from 'react';
import {
  View,
  Text,
  Button,
} from 'react-native';

class Parents extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }
    componentDidMount() {

    }
    
    handleCancel = (e) => {
        console.log('父组件的方法被子组件调用');
    }

    childClick = (e) => {
        this.child.onShow()
    }
    render() {
        return (
            <View>
                <Child onCancel={this.handleCancel} onRef={(ref)=>{ this.child = ref}}></Child>
                <Button onClick={this.childClick}>调用子组件的函数</Button>
            </View>
        );
    }
}

export default Parents;

// 子组件

import React, {Component} from 'react';
import {
  View,
  Button,
} from 'react-native';

class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    componentDidMount() {
        this.props.onRef(this)
    }
    
    onShow(){
        console.log('子组件的方法被父组件调用')
    }

    render() {
        return (
            <View>
                <Button onClick={()=>{this.props.handleCancel()}}>子组件用this.props调用父组件的函数</Button>
            </View>
        );
    }
}

export default Child;

猜你喜欢

转载自blog.csdn.net/khadijiah/article/details/111565991