react native中封装别的插件,在父组件中调用子组件的ref

时间:2022-03-13 19:55:20

话不多说,直接上代码:

父组件中:

import MyToast from '../../myToast';

<MyToast onRef={toast => this.toast = toast} position="center" />

子组件中:

import React from 'react';
import Toast from 'react-native-easy-toast';
import {
    StyleSheet,
} from 'react-native';

export default class MyToast extends React.Component {
    componentDidMount() {
        const { onRef } = this.props;
        if (typeof onRef === 'function') onRef(this.toast);
    }
    render() {
        return (
            <Toast
                {...this.props}
                ref={toast => this.toast = toast}
                style={styles.toastStyle}
                textStyle={{color: '#4A90E2'}}/>
        );
    }
}

const styles = StyleSheet.create({
    toastStyle: {
        backgroundColor: '#FFFFFF',
    }
});

道理就是通过onRef方法,采用回调的方式,让父组件得到子组件里Toast的ref。