如何检索由上一个函数创建的元素的parentId



我正在尝试构建一个小型React.js克隆,

在下面的代码片段中,我制作了一个简单的组件树,其中包含一系列功能组件

function Text(props) {
return createElement('p', null, props.content)
}
function Hello(props) {
return createElement(Text, props.content, null)
}
function Home() { // this is the root element
return createElement('div', null, 
createElement(Hello, {content: "hello world 1"}, null),
createElement(Hello, {content: "hello world 2"}, null)
)
}

createElement函数检查当前节点的类型,为其分配一个id,并将其推送到data数组中。但是,要重新构建组件树,我需要获得已被推送到数据中的每个组件的parentId。

我假设如果i的值为零,则意味着当前元素是根元素。但如果没有,如何找到创建当前元素的父元素的id

const data = [];
let i = 0;
function createElement(node, props, children) {
if(typeof node === "string") {
data.push({ name: node, id: i, parentId: i > 0 ? i : null });
i++;
};

if(typeof node === "function") {
let functionalComponent = constructFunctionComponent(node);
data.push({ name: node.name, id: i, parentId: i > 0 ? i : null });
i++;
createElement(functionalComponent(props)());
};
}
function constructFunctionComponent(fc) {
return (props) => (children) => fc(props, children);
}

如果我们执行Home()函数,以下是console.log显示的内容。这里的parentId密钥显然都是假的(除了第一个密钥,因为它是根元素(


// current output :
// note that here the parentId keys of each index are not correct (this is what i'm trying to resolve)
[
{ name: 'Home', id: 0, parentId: null },
{ name: 'Hello', id: 1, parentId: 1 },
{ name: 'Text', id: 2, parentId: 2 },
{ name: 'p', id: 3, parentId: 3 },
{ name: 'Hello', id: 4, parentId: 4 },
{ name: 'Text', id: 5, parentId: 5 },
{ name: 'p', id: 6, parentId: 6 },
{ name: 'div', id: 7, parentId: 7 }
]
// expected output:
// here, each parentId keys is a "reference" to the parent that added the index to the array
[
{ name: 'Home', id: 0, parentId: null },
{ name: 'Hello', id: 1, parentId: 7 },
{ name: 'Text', id: 2, parentId: 1 },
{ name: 'p', id: 3, parentId: 2 },
{ name: 'Hello', id: 4, parentId: 7 },
{ name: 'Text', id: 5, parentId: 4 },
{ name: 'p', id: 6, parentId: 5 },
{ name: 'div', id: 7, parentId: 0 }
]

我做了一个代码沙盒,里面有代码。如有任何帮助,我们将不胜感激!

以下是代码的链接Sandbox示例

谢谢,

现在,结构是从叶节点开始计算的,因此在创建每个元素时,父ID是未知的。您必须将ID的生成与元素的生成分开。以下是我的意思的一个例子(它不漂亮;你可能会想出一个更优雅的方法来做到这一点(:

function createElement(node, props, children) {
if(typeof node === "string") {
data.push({ name: node, id: props.id, parentId: props.parentId });
};

if(typeof node === "function") {
let functionalComponent = constructFunctionComponent(node);
data.push({ name: node.name, id: props.id, parentId: props.parentId });
createElement(functionalComponent(props)());
};
}
function Home() {
homeId = 0;
createElement
(
'div',
homeId,
createElement(Hello, {content: "hello 1", parentId: homeId, id: (hello1Id = ++homeId)}),
createElement(Hello, {content: "hello 2", parentId: homeId, id: (hello2Id = ++hello1Id)})
);
}

现在,ID是作为createElement调用的一部分创建的,因此它可以被知道并用于任何进一步的子创建。

最新更新