網站搜尋

reactjs - 在 React 中使用 TypeScript 的 React.memo


我在一個 .tsx 文件(React TypeScript)中使用 React.memo()

現在我已經為 Props 宣告了一個介面,如下:

interface Props {
  type?: string;
}

我的組件看起來像:

const Component: React.SFC<Props> = props => {
  /// return something;
};

export default memo(Component);

由於 type 是一個可選的屬性,我打算只在有時候使用它。

如果我把我的元件用作 <Component type="something" /> 一切正常。但如果我把它用作 <Component /> 我就會遇到錯誤 -->

Type '{ children: string; }' 與型別 'IntrinsicAttributes & Props' 沒有共同的屬性。

這似乎是一個非常荒謬的錯誤,因為我已經在 Code sandbox 上嘗試過,一切運作正常。有誰對這個錯誤可能是什麼有任何想法嗎?

更新

如果我在介面中明確添加一個屬性,如

interface Props {
  type?: string;
  children?: ReactNode;
}

那樣的話一切都正常。這本應該是隱含的,但根據錯誤訊息,它被認為是

'{ children: string; }'

有任何想法嗎???

答案#1

我相信在打字上有一個錯誤。正在更改

function memo<P extends object>(
  Component: SFC<P>,
  propsAreEqual?: (
    prevProps: Readonly<PropsWithChildren<P>>,
    nextProps: Readonly<PropsWithChildren<P>>
  ) => boolean
): NamedExoticComponent<P>;

到

function memo<P extends object>(
  Component: SFC<P>,
  propsAreEqual?: (
    prevProps: Readonly<PropsWithChildren<P>>,
    nextProps: Readonly<PropsWithChildren<P>>
  ) => boolean
): NamedExoticComponent<PropsWithChildren<P>>;

解決了這個問題

更新

其實,這不是一個錯誤。請參閱討論。

摘要:你必須在元件屬性類型中指定 children。

type MyComponentProps {
  children: React.ReactNode;
}

閱讀更多