【问题标题】:Can anyone help me to understand why `prefix` does not work when `suffix` does and how to fix this?谁能帮我理解为什么在“后缀”起作用时“前缀”不起作用以及如何解决这个问题?
【发布时间】:2021-10-24 11:00:22
【问题描述】:

我想我了解prefix react prop 与此处的 html 属性 prefix 发生冲突。

我不明白为什么 typescript 使用 html prefix 当这是一个 react prop?

谢谢

https://codesandbox.io/s/typescript-playground-export-forked-qb0nd?file=/index.tsx

import React, { forwardRef, LegacyRef } from "react";

type Props = React.LiHTMLAttributes<HTMLLIElement> & {
  prefix?: React.ReactNode;
  suffix?: React.ReactNode;
};

const SubMenu: React.ForwardRefRenderFunction<unknown, Props> = (
  { prefix, suffix },
  ref
) => {
  const subMenuRef: LegacyRef<HTMLLIElement> =
    (ref as any) || React.createRef<HTMLLIElement>();

  return <li ref={subMenuRef}>hello</li>;
};

const SubMenuEl = forwardRef<unknown, Props>(SubMenu);

export function App() {
  return <SubMenuEl prefix={<div>bb</div>} suffix={<div>aa</div>} />;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

【问题讨论】:

标签: html reactjs typescript typeerror


【解决方案1】:

因为您使用的是交集类型&amp;,如果两种类型具有相同的字段名称,它的工作方式就是这样。你可以这样避免:

type Props = Omit<React.LiHTMLAttributes<HTMLLIElement>, 'prefix'> & {
  prefix?: React.ReactNode;
  suffix?: React.ReactNode;
};

【讨论】:

  • 请不要回答不符合规则的问题。一个问题应该是自我维持的,在这种情况下,需要一个minimal reproducible example 在问题本身,而不仅仅是指向外部资源的链接(不能保证总是显示相同的内容当问题被问到时,或者只要这个问题就会出现)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 2011-01-16
  • 1970-01-01
相关资源
最近更新 更多