2

我需要绑定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了,但是typescript总是提示我缺少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组件太常见了。

我怎么解决这个问题?

4

1 回答 1

1

基于这个 github 问题其中报告的解决方案,您可以通过将组件类型转换为 WrapperInstance 来解决上述问题

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;
于 2021-03-15T07:35:56.140 回答