话不多说,直接上代码:
父组件中:
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。