类组件通过ref操作函数组件
子组件:
// forwardRef:react内部封装过的HOC
// useImperativeHandle:自定义暴露给父组件的实例值
import React, { forwardRef, useImperativeHandle, } from 'react';
let Children = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
init
}));
function init(){
console.log('init')
}
}))
父组件:
class Parent extends React.Component{
constructor(props) {
super(props);
this.child = createRef();
}
<Children ref={this.child} />
}
通过this.child.current.init() 就可以调用子组件的方法了