chdyiboke / weekly

issue and share weekly
5 stars 1 forks source link

react hooks 父组件调用子组件方法 #60

Open liukexina opened 3 years ago

liukexina commented 3 years ago

父组件使用 useRef 创建一个 ref 传入子组件:

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

子组件需要使用 useImperativeHandle 暴露 ref 自定义的实例值给父组件:

function children(props, ref) {
    useImperativeHandle(ref, () => ({
        hello: () => console.log('hello world!')
    }))
    return <h1>children</h1>
}

父组件调用子组件方法:

const childrenRef = useRef(null);
const something = () => childrenRef.current.hello();