为什么 React 路由器 Link 组件在用作变量 JSX 构造函数时不接受子组件?

huangapple go评论56阅读模式
英文:

Why does the react router Link component not accept children when used as a variable JSX constructor?

问题

我可以如下使用 Link,没有问题。它接受子元素。

import { Link } from 'react-router-dom';

<Link to=''>
    {content}
</Link>

我也可以以同样的方式使用 &lt;button&gt;

<button>
    {content}
</button>

我可以有条件地构建一个 Linkbutton,没有问题。

import { Link } from 'react-router-dom';

const MyElement = condition ? Link : 'button';

<MyElement />

然而,一旦我添加子元素,就会出现问题。

import { Link } from 'react-router-dom';

const MyElement = condition ? Link : 'button';

<MyElement>
    {content}
</MyElement>
类型 ' { children: MyElement; } ' 与类型 'IntrinsicAttributes' 没有共同的属性。

我不明白这里的 TS 类型是如何工作的,不允许在变量组件中使用子元素。

我使用的是 react-router-dom 版本 5.3.4。

英文:

I can use Link as follows with no issues. It accepts children.

import { Link } from &#39;react-router-dom&#39;;

&lt;Link to=&#39;&#39;&gt;
    {content}
&lt;/Link&gt;

I can also use a &lt;button&gt; the same way.

&lt;button&gt;
    {content}
&lt;/button&gt;

I can conditionally construct a Link or button with no problems.

import { Link } from &#39;react-router-dom&#39;;

const MyElement = condition ? Link : &#39;button&#39;;

&lt;MyElement /&gt;

However, once I add children I get an issue.

import { Link } from &#39;react-router-dom&#39;;

const MyElement = condition ? Link : &#39;button&#39;;

&lt;MyElement&gt;
    {content}
&lt;/MyElement&gt;
Type &#39;{ children: MyElement; }&#39; has no properties in common with type &#39;IntrinsicAttributes&#39;.

I don't understand how the TS types are working here to not allow children in the variable component.

I am using react-router-dom version 5.3.4.

答案1

得分: 2

To resolve this issue, you can explicitly type the MyElement variable using the React.ElementType type from React.

import { Link } from 'react-router-dom';
import React from 'react';

const MyElement: React.ElementType = condition ? Link : 'button';

<MyElement>
  {content}
</MyElement>
英文:

To resolve this issue, you can explicitly type the MyElement variable using the React.ElementType type from React.

import { Link } from &#39;react-router-dom&#39;;
import React from &#39;react&#39;;

const MyElement: React.ElementType = condition ? Link : &#39;button&#39;;

&lt;MyElement&gt;
  {content}
&lt;/MyElement&gt;

huangapple
  • 本文由 发表于 2023年6月8日 00:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定