首页 > 解决方案 > useImperativeHandle 上的流类型出现模棱两可的错误,无法解决

问题描述

我有一个使用useImperativeHandle的功能组件,

const ConfirmActionModal = (props: Props, ref) => {
  const [isVisible, setIsVisible] = useState(false)

  const showModal = () => {
    setIsVisible(true)
  }

  useImperativeHandle(ref, () => {
    return {
      showModal: showModal
    }
  })

  ...
  return (
      // html
  )
}

export default forwardRef<Props, void>(ConfirmActionModal)

我收到流式错误

Cannot call useImperativeHandle with function bound to create because:
 • object literal [1] is incompatible with enum [2] in the return value.
 • object literal [1] is incompatible with enum [3] in the return value.

        src/apps/orders/ConfirmActionModal.js
         57│   //   }
         58│   // })
         59│
    [1]  60│   useImperativeHandle(ref, () => ({
         61│     showModal() {
         62│       showModal()
         63│     }
         64│   }))
         65│
         66│   const node: { current: null | HTMLDivElement } = useRef(null)
         67│   const stateRef = useRef(isVisible)

        /tmp/flow/flowlib_1890a56b/react.js
 [3][2] 292│       ref: {current: null | Instance} | ((null | Instance) => mixed),



Found 2 errors

据我了解,流中定义的类型如下

  declare export function useImperativeHandle<T>(
    ref: {current: T | null} | ((inst: T | null) => mixed) | null | void,
    create: () => T,
    inputs: ?$ReadOnlyArray<mixed>,
  ): void;

不适用于 forwardRef 的定义

  declare export function forwardRef<Config, Instance>(
    render: (
      props: Config,
      ref: {current: null | Instance} | ((null | Instance) => mixed),
    ) => React$Node,
  ): React$AbstractComponent<Config, Instance>;

我发现了一个与此相关的 github问题,但对话并没有发展。此外,我从 flow it 中找到了这篇文章。

如果您的组件是一个函数,您可能需要重新考虑使用 forwardRef,因为函数组件的实例类型是 void。

我想知道为什么

PS 以下是反应源代码上的 userInperativeHandle 函数。那里没有类型信息。

function useImperativeHandle(ref, create, inputs) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useImperativeHandle(ref, create, inputs);
}

标签: reactjsflowtype

解决方案


推荐阅读