【发布时间】:2021-10-02 07:57:36
【问题描述】:
我有这个对象需要发送到组件。
{
key: "1",
label: "Folder 7",
icon: "fa fa-folder",
title: "Desktop Folder",
children: [
{
key: "1-0",
label: "Folder 8",
icon: "fa fa-folder",
title: "Documents Folder",
},
{
key: "1-1",
label: "Folder 9",
icon: "fa fa-folder",
title: "Documents Folder",
},
],
}
我为它写了这个界面:
interface Node {
node: {
key: string
label: string
icon: string
title: string
children: Array<Node>
}
}
但这会报错
类型“{}”缺少类型“{ key: string;”中的以下属性标签:字符串;图标:字符串;标题:字符串;孩子:节点[]; }':键、标签、图标、标题、子项
我从中传递道具的组件:
interface TreeProps{
data: Array<object>
}
const Tree: FC<TreeProps> = ({data=[]}) => {
return (
<div>
<div className="d-tree">
<ul className="d-flex d-tree-container flex-column">
{data.map(tree => (
<TreeNode node={tree}/>
))}
</ul>
</div>
</div>
)
}
我在 prop 中使用的组件:
type Node = {
node: {
key: string
label: string
icon: string
title: string
children: Node[]
}
}
const TreeNode: FC<Node> = ({node}) => {
const [childVisiblity, setChildVisibility] = useState(false);
const hasChild = node.children ? true : false;
return (
<li className="d-tree-node border-0">
<div className="d-flex" onClick={e => setChildVisibility(!childVisiblity)}>
{hasChild && (
<div className={`d-inline d-tree-toggler ${childVisiblity ? "active" : "" }`}>
<FontAwesomeIcon icon={faCaretRight}/>
</div>
)}
<div className="col d-tree-head">
<i className={`mr-1 ${node.icon}`}></i>
{node.label}
</div>
</div>
{
hasChild && childVisiblity && <div className="d-tree-content">
<ul className="d-flex d-tree-container flex-column">
<Tree data={node.children}/>
</ul>
</div>
}
</li>
)
}
我需要告诉组件数组有对象吗?我该如何解决这个问题?
【问题讨论】:
-
为什么
Node接口里面有node属性,而你的数据没有node属性? -
``` const TreeNode: FC
= ({node}) => { } ``` 在下面需要它,每个孩子也是节点类型,但我如何分配这些道具的类型作为对象而不使用变量?
标签: javascript reactjs typescript