子组件不渲染

时间:2020-10-29 13:50:19

标签: reactjs

我正在尝试呈现按 level 分组的数据数组。 通常,数据如下所示:

let education: [
        { id: 1, level: "phD", institution: "University A", country: "USA" },
        { id: 2, level: "MSc", institution: "University B", country: "Switzerland" },
        { id: 3, level: "MSc", institution: "University C", country: "Switzerland" },
      ]

主要外观如下:

import React from "react";
import EducationHeader from "./EducationHeader";
import EducationItem from "./EducationItem";

export default function Education({ education, educationUpdateFn }) {
  let listOfLevels = education.map((item) => item.level);
  // sort and remove duplicates
  listOfLevels = listOfLevels
    .sort()
    .filter((v, i) => listOfLevels.indexOf(v) === i);

  return (
    <div>
      {listOfLevels.map((level) => (
        <EducationHeader key={level} name={level}>
          {education
            .filter((item) => item.level === level)
            .map((item) => {
              return (
                <EducationItem
                  key={item.id}
                  institution={item.institution}
                  country={item.country}
                />
              );
            })}
        </EducationHeader>
      ))}
    </div>
  );
}

反过来,EducationHeader真的很简单:

import React from "react";

export default function EducationHeader({ name }) {
  return <h2>{name}</h2>;
}

并且EducationItem也很简单:

import React from "react";

export default function EducationItem({ institution, country }) {
  return (
    <div>
      {institution} - {country}
    </div>
  );
}

不幸的是,EducationItem组件无法呈现。

我觉得我在EducationHeader渲染中犯了一个非常基本的错误(例如用于渲染子项的占位符),但我无法查明

2 个答案:

答案 0 :(得分:0)

EducationHeader组件的开始和结束标记之间的所有内容都将作为EducationHeader对象上的children属性传递给props组件。

因此,要渲染EducationItem组件,您需要在props.children组件中渲染EducationHeader

function EducationHeader({ name, children }) {
  return (
    <div>
     <h2>{name}</h2>
     { children }
    </div>
  );
}

有关详细信息,请参见:React - props.children

答案 1 :(得分:0)

您是对的,这很简单。您只需要告诉您的<EducationHeader />组件即可实际渲染其子代。也许是这样的:

export default function EducationHeader({ name, children }) {
  return (
    <>
      <h2>{name}</h2>
      <div>{children}</div>
    </>
  );
}

无论您将{children}放置在组件中的何处,标题的子项都将呈现。