0

我有一个嵌套的数据结构,我从一个包含文本部分作为数组内的对象的 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."
      ]
    }
  ]
}
4

2 回答 2

0

将“text”替换为复制数组并将内容映射到 p 标记,类似于您在 body 标记上所做的操作

于 2021-03-03T16:48:14.490 回答
0

弄清楚我做错了什么,并且能够通过将所有元素推送到我的函数中的第二个数组并像这样返回该新数组来正确显示所有元素:

function renderElement(sections) {
  const elements = []
  
  if (sections) {
    sections.map((section) => {
      switch (section.textType) {
        case "title":
          return elements.push(section.copy.map((string) => <Title>{string}</Title>));
        case "subtitle":
          return elements.push(section.copy.map((string) => <Subtitle>{string}</Subtitle>));
        case "body":
          return elements.push(section.copy.map((string) => <Body>{string}</Body>));
        default:
          return section.copy;
      }
    });
  }
  return elements
}
于 2021-03-03T19:54:33.140 回答