@DanceMonkeyTime

Как рекурсивно зарендерить компоненту?

Есть следущая структура:
[{
        "id": "market-executive-summary",
        "title": "Executive Summary",
        "interactivity": false,
        "priceFactor": 2,
        "children": [{
            "id": "market-executive-summary-overview",
            "title": "Overview",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }, {
            "id": "market-executive-summary-key-findings",
            "title": "Key Findings",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }, {
            "id": "market-executive-summary-conclusions-implications",
            "title": "Conclusions & Implications",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }]
    },
    {
        "id": "market-definitions-segmentation",
        "title": "Definitions & Segmentation",
        "interactivity": false,
        "priceFactor": 2,
        "children": [{
            "id": "market-definitions-segmentation-definitions",
            "title": "Definitions",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }]
    }
]


Мне нужно рекурсивно рендерить children, посколько может в будущем строиться дерево.

Сейчас у меня так:

{tags?.map((tag: IPresetTag) => (
          <PresetTags {...tag} />
 ))}

export const PresetTags = ({ title, interactivity, children }: IPresetTag) => {
  return (
    <Accordion title={title} interactivity={interactivity}>
      <List>
        {children.map((tag: IPresetTag) => (
          <PresetTagContent button key={tag.id}>
            <CheckMark />
            <ListItemText>{tag.title}</ListItemText>
          </PresetTagContent>
        ))}
      </List>
    </Accordion>
  );
};
  • Вопрос задан
  • 49 просмотров
Решения вопроса 1
@twoone
Лучше рекурсию прямо на компонентах реализовать -

https://codesandbox.io/s/silly-ramanujan-3giij?fil...

import React from "react";
import "./styles.css";

const data = [{
        "id": "market-executive-summary",
        "title": "Executive Summary",
        "interactivity": false,
        "priceFactor": 2,
        "children": [{
            "id": "market-executive-summary-overview",
            "title": "Overview",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }, {
            "id": "market-executive-summary-key-findings",
            "title": "Key Findings",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }, {
            "id": "market-executive-summary-conclusions-implications",
            "title": "Conclusions & Implications",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }]
    },
    {
        "id": "market-definitions-segmentation",
        "title": "Definitions & Segmentation",
        "interactivity": false,
        "priceFactor": 2,
        "children": [{
            "id": "market-definitions-segmentation-definitions",
            "title": "Definitions",
            "interactivity": false,
            "priceFactor": 0,
            "children": []
        }]
    }
]

const List = ({data}) => {
  let children = data.map(data => <Item {...data}/>)
  
  return (
    <ul id>
      {children}
    </ul>
  );
}
const Item = ({id, title, children}) => {
  let list = children.length ? <List data={children}/> : null;
  
  return (
    <li>
      <span>{title}</span>
      {list}
    </li>
  );
}

export default function App() {
  return (
    <List data={data}/>
  );
}
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
locky_yotun
@locky_yotun
Я видел некоторый джаваскрипт
Как-то так: https://codesandbox.io/s/mystifying-burnell-zqkxo?...

const renderRecursive = (Class, data) => {
  return data.map(item => <Class {...item} key={item.id} />);
};

const Item = ({ id, children }) => {
  const style = { textAlign: "left" };
  const item = <div style={style}>{id}</div>;
  let childrenList = null;

  if (children && children.length) {
    childrenList = <ul>{renderRecursive(Item, children)}</ul>;
  }

  return (
    <li>
      {item}
      {childrenList}
    </li>
  );
};

export default function App() {
  return <ul className="App">{renderRecursive(Item, data)}</ul>;
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы