TS函数组件中父组件调用子组件
程序员文章站
2022-07-02 22:13:43
...
需要用的api
forwardRef
&& useImperativeHandle
父组件
import React, { useRef } from 'react';
import { Button } from 'antd';
import Child from './Children';
interface ReturnVoid {
getValues: () => void
}
const ForwordRef: React.FC<any> = () => {
const childRef = useRef<ReturnVoid>(null);
const onBtnClick = () => {
if (childRef && childRef.current) {
const text = childRef.current.getValues();
console.log(text);
}
}
return (
<>
<Button type="primary" onClick={() => { onBtnClick() }}>调用子组件方法</Button>
<Child ref={childRef} />
</>
)
}
export default ForwordRef;
子组件
import React, { forwardRef, useImperativeHandle } from 'react';
// ref必须
const ForwordRef = (props: any, ref: any) => {
useImperativeHandle(ref, () => ({
getValues: () => {
return ('hell word')
}
}))
return (
<>
<p>我是子组件</p>
</>
)
}
export default forwardRef(ForwordRef);