【发布时间】:2020-11-23 11:20:28
【问题描述】:
我想定义一个父元素,我需要在其中传递一些反应元素作为道具。我想对子组件的道具添加一些要求,但我无法让我的打字稿完全按预期工作。这是一个最小的例子
import * as React from "react";
function JSXElementChild() {
return <div>Child One</div>;
}
const ReactFCChild: React.FC<{ label: string }> = ({ label }) => {
return <div>{label}</div>;
};
function Parent({
children
}: {
children: React.ReactElement<{ label: string }>[];
}) {
return (
<div>
{children.map((child) => (
<div key={child.props.label}>{child}</div>
))}
</div>
);
}
export default function App() {
return <Parent children={[<JSXElementChild />, <ReactFCChild />]} />;
}
Parent 组件需要 children 作为道具,而这些子组件需要 label: string 作为道具。现在上面确实正确标记了ReactFCChild 的打字稿问题; Property 'label' is missing in type '{}' but required in type '{ label: string; }'.ts(2741)。但是JSXElementChild 不会产生任何问题。如何解决?
【问题讨论】:
标签: reactjs typescript