我有一个嵌套的数据结构,我从一个包含文本部分作为数组内的对象的 API 返回。
我正在尝试遍历部分的初始数组,检查该部分的类型,然后根据类型遍历复制数组以设置样式并将每个字符串呈现为适当的 HTML 元素。
我遇到的问题是我试图通过使用 map 来完成此操作,然后使用 switch 语句,然后为每个复制部分使用另一个 map,并且没有呈现任何内容。
这是我创建的一个CodeSandbox作为问题的模型
这是我当前的组件:
import React from "react";
import styled from "styled-components";
function renderElement(sections) {
if (sections) {
sections.map((section) => {
switch (section.textType) {
case "title":
return section.copy.map((text) => <Title>{text}</Title>);
case "subtitle":
return section.copy.map((text) => <Subtitle>{text}</Subtitle>);
case "body":
return section.copy.map((text) => <Body>{text}</Body>);
default:
return section.copy;
}
});
}
}
const TextComponent = (props) => {
const { sections } = props;
return <>{renderElement(sections)}</>;
};
export default TextComponent;
const Title = styled.h1`
font-size: 28px;
`;
const Subtitle = styled.h4`
font-size: 22px;
`;
const Body = styled.p`
font-size: 16px;
`;
这是数据结构:
const data = {
sections: [
{
textType: "title",
copy: ["Doctor Strange"]
},
{
textType: "subtitle",
copy: ["As Earth’s Sorcerer Supreme, Doctor Strange wields arcane spells and mystical artifacts to defend the planet against malevolent threats.", "The one who protects your reality"]
},
{
textType: "body",
copy: [
"Recognized the world over as one of the most brilliant neurosurgeons, Stephen Strange’s arrogance and self-centered nature grew alongside his skill until his ego far outweighed his career.",
"Knowing his reliance on his medical abilities to support his affluent lifestyle, Strange began to seek a source of healing for his hands until the quest drained him of his resources and he faced a dark and uncertain future."
]
}
]
}