应用场景
父级需要调用子组件的某函数
实现步骤
案例:创建自定义按钮
button.tsx
ts
import { Ref, forwardRef, useImperativeHandle,ReactNode} from "react"
declare type ButtonProps = {
/**按钮文字 */
children?: ReactNode,
onClick?: () => void
}
/**组件对外提供的可访问内容*/
export declare type ButtonInstance = {
/**触发按钮点击事件*/
forceClick: () => void;
}
/**自定义按钮组件 */
const Button = forwardRef((props: ButtonProps, ref: React.Ref<ButtonInstance | undefined>) => {
function handleClick() {
alert('子组件的事件被触发')
if (props.onClick) {
props.onClick();
}
}
//声明可以被访问的内容
useImperativeHandle(ref, () => {
return {
forceClick:handleClick
}
});
return (
<button onClick={handleClick}>{props.children}</button>
);
});
export default Button;
父组件中调用子组件的函数
parent.tsx
ts
import Button from './button.tsx'
import {useState} from 'react'
const Parent=()=>{
const [buttonInstance,setButtonInstance]=useState<ButtonInstance|null>()
function handleParentClick(){
buttonInstance?.forceClick()
}
return (
<>
<button onClick={handleParentClick}>父组件的原生按钮</button>
<Button ref={setButtonInstance}>自定义的按钮组件</Button>
</>
)
}
export default Parent