使用forwardRef后如何将组件绑定到组件?

How to bind components to component after using forwardRef?

我需要将 TitleBody 组件绑定到 Wrapper 组件。

之前,我的组件是这样写的:

import { FC } from 'react';

// need bound components
const Title: FC<...> = () => {...}
const Body: FC<...> = () => {...}

interface WrapperProps{...}
interface WrapperInterface extends FC<WrapperProps>{
  Title: typeof Title // bind Title component
  Body: typeof Body // bind Body Component
}
const Wrapper: WrapperInterface = () => {...}

Wrapper.Title = Title;
Wrapper.Body = Body;

使用forwardRef后,我修改了WrapperInterface,但是打字稿总是提示我缺少TitleBody属性,这是WrapperInterface代码:

import { ForwardRefExoticComponent, RefAttributes, forwardRef } from 'react'

// need bound components
const Title: FC<...> = () => {...}
const Body: FC<...> = () => {...}

interface WrapperRef{...}
interface WrapperProps{...}
interface WrapperInstance extends ForwardRefExoticComponent<WrapperProps & RefAttributes<WrapperRef>>{
  Title: typeof Title // bind Title component
  Body: typeof Body // bind Body Component
}

const Wrapper: WrapperInstance = forwardRef((props, ref) => {...});
// TS2739: Type 'ForwardRefExoticComponent  >' is missing the following properties from type 'WrapperInterface': Title, Body
Wrapper.Title = Title;
Wrapper.Body = Body;

没有直接导出,因为 BodyTitle 组件太常见了。

我该如何解决这个问题?

基于this github issue and the solution reported in it,可以通过将组件类型转换为WrapperInstance like

来解决上述问题
import { ForwardRefExoticComponent, RefAttributes, forwardRef } from 'react'

// need bound components
const Title: FC<...> = () => {...}
const Body: FC<...> = () => {...}

interface WrapperRef{...}
interface WrapperProps{...}
interface WrapperInstance extends ForwardRefExoticComponent<WrapperProps & RefAttributes<WrapperRef>>{
  Title: typeof Title // bind Title component
  Body: typeof Body // bind Body Component
}

const Wrapper = forwardRef<WrapperRef, WrapperProps>((props, ref) => {...}) as WrapperInstance;
Wrapper.Title = Title;
Wrapper.Body = Body;