用rollup打包后的组件无法用ref获取到实例

我编写了一个函数式组件,

import React, { useRef,forwardRef,useEffect,useImperativeHandle, } from 'react';
function ShowComponent(props:any, ref:any){
  useImperativeHandle(ref, () => ({
    focus: () => {
      console.log(2222)
    }
  }));
  return <div>111</div>
}
export default forwardRef(ShowComponent)

然后用rollup打包,打包的核心配置如下,打包后的文件名为runtime.js

  output: {
      format: "umd",
      file: join(inprocessDir, `runtime.js`),
      sourcemap: !production ? "inline" : false,
      name: `${widgetPackage}.${widgetName}.runtime`,
      // globals
    },

当我在实际项目中引用我的这个组件时,

import React, { useRef,forwardRef,useEffect,useImperativeHandle } from 'react';
import ShowComponent from './runtime.js';

export default function Demo() {
    useEffect(()=>{
      console.log(ShowComponent,111)
    })
    const instance=useRef();
    return (
      <div>
        <ShowComponent ref={instance}></ShowComponent>
      </div>
    );
}

通过log,我发现通过import 引入的组件是一个函数,导致我无法通过ref获取到组件的实例

t=>r.createElement(n,l(a({},t),{reversal:!1})) 111

请问,我该怎么做才能通过ref获取到ShowComponent的实例呢
ps:
1 把ShowComponent改写成Class Component没有用,import进来的还是一个函数
2 rollupConfig 的format 改写成esm 也不起作用,打包完输出的也还是一个函数

阅读 1.1k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题