[英]Inject a React component as a prop when it has mandatory props in Typescript
I'm building a React
TreeView
component with Typescript
.我正在使用
Typescript
构建一个React
TreeView
组件。 I would like the flexibility to be able to inject a template TreeNode
component that renders each node.我希望能够灵活地注入呈现每个节点的模板
TreeNode
组件。
How can I type my TreeNode
's props so I can inject TreeNode
into TreeView
as a prop without typescript
complaining that I'm not providing my TreeNode
s props yet, even though they will be down the road when TreeView
builds the hierarchy and feeds each TreeNode
with appropriate props
.我如何输入我的
TreeNode
的道具,以便我可以将TreeNode
作为道具注入到TreeView
,而无需typescript
抱怨我还没有提供我的TreeNode
的道具,即使当TreeView
构建层次结构并提供每个道具时它们将在路上带有适当props
TreeNode
。
I tried to strip down my code to the minimum:我试图将我的代码精简到最低限度:
interface TreeNodeProps {
id: string
title: string
}
const TreeNode: React.SFC<TreeNodeProps > = (props) => {
return (
<div key={props.id}>
<div>{props.title}</div>
<div>{props.children}</div>
</div>
)
}
const TreeView: React.SFC<{treeData: any, TreeNode: JSX.Element}> = (props) => {
// here's the logic where each TreeNode's props will be fed with graph's props.
const buildTreeRecursively = (treeData) =>
treeData.map((node) => {
if (node.children.length > 0) {
return (
<TreeNode id={node.id} title={node.title}>
{buildTreeRecursively(node.children)}
</TreeNode>
)
}
return <TreeNode id={node.id} title={node.title} />
})
return (
<div className={styles.treeView}>
{buildTreeRecursively(props.treeData)}
</div>
)
}
This seems to work:这似乎有效:
const buildTreeRecursively = (treeData: React.PropsWithChildren<TreeNodeProps>[]) =>
treeData.map((node) => {
if (node.children) {
return (
<TreeNode id={node.id} title={node.title}>
{buildTreeRecursively(node.children as React.PropsWithChildren<TreeNodeProps>[])}
</TreeNode>
)
}
return <TreeNode id={node.id} title={node.title} />
})
If I leave the if (node.children.length > 0)
, I get the compile error如果我离开
if (node.children.length > 0)
,我会收到编译错误
Object is possibly 'null' or 'undefined'.
对象可能是“空”或“未定义”。
and since the type of node.children
is a superset of React.PropsWithChildren<TreeNodeProps>[]
, we have to cast it since we know we're only using that subset of the type.并且因为
node.children
的类型是React.PropsWithChildren<TreeNodeProps>[]
的超集,我们必须转换它,因为我们知道我们只使用该类型的子集。
I got the idea for treeData
's type by looking at the type hint for props
from通过查看
props
的类型提示,我得到了treeData
类型的想法
const TreeNode: React.SFC<TreeNodeProps> = (props) => {
return (
<div key={props.id}>
<div>{props.title}</div>
<div>{props.children}</div>
</div>
)
}
which was React.PropsWithChildren<TreeNodeProps>
.这是
React.PropsWithChildren<TreeNodeProps>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.