我有一个需要递归呈现的项列表。我能把它渲染成一级。有人能帮我解决嵌套递归吗。我在一个功能组件中发布了相关功能。注意,details
已存储在状态变量details
{
"details": [{
"title": "Part-1",
"content": [{
"type": "text",
"content": "TextABC"
}]
}, {
"title": "Part-2",
"content": [{
"type": "text",
"content": "TextXYZ"
}, {
"type": "list",
"content": [{
"text": "TextLMN",
"type": "text"
}, {
"type": "list",
"content": [{
"text": "TextPQR",
"type": "text"
}, {
"text": "TextDEF",
"type": "text"
}]
}]
}]
}, {
"title": "Part-3",
"content": [{
"type": "list",
"content": ["<a target='_blank' href='https://www.example.com'>ABC</a>", "<a target='_blank' href='https://www.example1.com'>XYZ</a>"]
}]
}]
}
每个Item都可以用text或list类型引用。我尝试了以下方法,但嵌套列表的项目不工作
const isAnchor = str => {
return /^<a.*>.*</a>/i.test(str);
};
const getContentJsx = (value) => {
return isAnchor(value) ? (
<li dangerouslySetInnerHTML={{ __html: sanitize(value) }} />
) : (
<li>{value}</li>
);
};
const getDetailJsx = () => {
return details.map(({ title, content }, index) => {
return (
<div key={`${title}${index}`}>
<h6>
<span>{title}</span>
</h6>
{content?.map(({ type: mainType, content: data }) => (
<div>
{mainType === "text" && <p>{data}</p>}
{mainType === "list" && <ul>{data?.map((contentValue) => getContentJsx(contentValue))}</ul>}
</div>
))}
</div>
);
});
};
return (
<div>
<>
{getDetailJsx()}
</>
)}
</div>
);
如建议的那样,您可以创建一个递归组件来包装逻辑,并使递归调用成为可能。首先,我必须纠正你的detail
对象。它的属性不一致。注意,例如,text
->content
:
"type": "text",
"text": "TextPQR"
"type": "text",
"content": "TextPQR"
此外,注意到它将涉及title
的部分从递归中分离出来,以方便其理解并使代码更清晰。
const getContentJsx = (value) => {
return isAnchor(value) ? (
<li dangerouslySetInnerHTML={{ __html: sanitize(value) }} />
) : (
<li>{recursive(value)}</li>
);
};
const getDetailJsx = () => {
return details.map(({ title, content }, index) => {
return (
<div key={`${title}${index}`}>
<h3>
<span>{title}</span>
</h3>
{recursive(content)}
</div>
)
})
}
const recursive = (content) => {
return (
<div>
{
content.map(({type: mainType, content: data}, index) => (
<div key={index}>
{mainType === "text" && <p>{data}</p>}
{mainType === "list" && <ul>{getContentJsx(data)}</ul>
}
</div>
))
}
</div>
)
也如这里所示