【问题标题】:React.memo with typescript in reactReact.memo 与打字稿反应
【发布时间】:2019-04-25 07:35:52
【问题描述】:

我在 .tsx 文件中使用 React.memo()(React 打字稿)

现在我已经为 Props 声明了一个接口:

interface Props {
  type?: string;
}

我的组件看起来像:

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

export default memo(Component);

现在由于 type 是一个可选的属性,我打算只偶尔使用它。

如果我将我的组件用作&lt;Component type="something" /&gt;,一切都会好起来的。 但是如果我将它用作&lt;Component /&gt; 我会得到错误-->

类型'{孩子:字符串; }' 与 type 没有共同的属性 '内在属性和道具'。

这似乎是一个非常荒谬的错误,因为我在代码沙箱上尝试过,一切正常。关于错误可能是什么的任何想法?

更新

如果我在界面中明确添加一个道具

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

那么在这种情况下一切正常。这应该是隐含的,但要根据错误将其视为

'{ 孩子:字符串; }'

有什么想法吗???

【问题讨论】:

  • 你试过重命名道具吗? React.memo 使用了一些称为 type 的属性。
  • codesandbox.io/embed/6lmwvxj0vk 但它在这个沙盒中有效。
  • 另外我尝试重命名。没用

标签: reactjs typescript


【解决方案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>>;

解决问题

更新

嗯,实际上这不是一个错误。见discussion。

TLTR:您必须在组件道具类型中指定children。

type MyComponentProps {
  children: React.ReactNode;
}

Read more

【讨论】:

  • React.SFC 已弃用。 React.FC 应该可以正常工作。此外,您可能不需要定义NamedExoticComponent,也不必在需要时扩展对象。但是,您应该定义您的接口和类型。
  • 使用memo 函数的示例将改进此答案
猜你喜欢
  • 1970-01-01
  • 2017-12-24
  • 2021-08-13
  • 2017-09-26
  • 2019-07-11
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
相关资源
最近更新 更多