React 中 关于 useImperativeHandle 的 TypeScript 类型声明

1,090 阅读1分钟

子组件

import { useImperativeHandle, forwardRef } from 'react';

export interface IRefProps {
  hello: () => void;
}

type Props = {};

const Child= forwardRef<IRefProps, Props>((props, ref) => {

  useImperativeHandle(
    ref,
    () => {
      return {
      	// 暴露 hello 方法给父组件
        hello: () => {
          console.log('hello');
        },
      };
    },
    []
  );

  return (
    <></>
  );
});

export default Child;

父组件

import { IRefProps } from '/preview/index';

const Father = () => {

	const childRef = useRef<IRefProps>(null);

	return(
		<>
			<Child ref={childRef} />
			<button onClick={() => previewRef.current?.hello()} >触发子组件的hello方法</button>
		</>
		
	)
}