react typescipt hook 实现父组件调用子组件(forwardRef,useImperativeHandle)

子组件

export interface MychildRef {
  childClick: () => void;
}
const Test = (props: {}, ref: React.Ref) => {
  const {
    data: userInfo,
    loading,
    run,
  } = useRequest(getUserInfo, {
    manual: true,
  });
  useImperativeHandle(ref, () => ({
    childClick: () => {
      clickHandle();
    },
  }));
  const [flag, { toggle }] = useBoolean(true);
  const clickHandle = () => {
    let text = flag ? "大可" : "小涛";
    run(text);
    toggle();
  };

  return (
    <>
      
      {loading ? 
loading...
:
Username: {userInfo?.name}
} ); }; export default forwardRef(Test);

父组件调用

function App() {
  const inputEl = useRef(null);
  const clickChildHandle = () => {
    inputEl.current?.childClick();
  };
  return (
    
); }

你可能感兴趣的:(react typescipt hook 实现父组件调用子组件(forwardRef,useImperativeHandle))