办法:

父组件应用 useRef 创立一个 ref 传入 子组件

...const childrenRef = useRef(null);...return <children ref={childrenRef} />复制代码

子组件须要应用 useImperativeHandle 裸露 ref 自定义的实例值给父组件。这个须要用 forwardRef 包裹着。

function children(props, ref) {    useImperativeHandle(ref, () => ({        hello: () => console.log('hello world!')    }))    return <h1>children</h1>}export default forwardRef(children);复制代码

那么在父组件怎么调用呢?

...const childrenRef = useRef(null);const something = () => childrenRef.current.hello();...复制代码

倡议:

还是能够查看一下实现办法的关键点: useRef, useImperativeHandle, forwardRef。其实是利用了 ref 不变的性质,将子组件的办法保留着,父组件能够调用。能够说,ref 作为父组件和子组件的一座由父组件达到子组件的桥梁(单向的,父->子)