英文:
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>
我也可以以同样的方式使用 <button>
。
<button>
{content}
</button>
我可以有条件地构建一个 Link
或 button
,没有问题。
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 'react-router-dom';
<Link to=''>
{content}
</Link>
I can also use a <button>
the same way.
<button>
{content}
</button>
I can conditionally construct a Link
or button
with no problems.
import { Link } from 'react-router-dom';
const MyElement = condition ? Link : 'button';
<MyElement />
However, once I add children I get an issue.
import { Link } from 'react-router-dom';
const MyElement = condition ? Link : 'button';
<MyElement>
{content}
</MyElement>
Type '{ children: MyElement; }' has no properties in common with type 'IntrinsicAttributes'.
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 'react-router-dom';
import React from 'react';
const MyElement: React.ElementType = condition ? Link : 'button';
<MyElement>
{content}
</MyElement>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论