【问题标题】:Rendering a component within another component在另一个组件中渲染一个组件
【发布时间】:2021-12-04 20:30:01
【问题描述】:

我正在尝试通过以下方式在另一个组件中呈现组件。即使我尝试在组件中呈现 div 元素,它也不会显示。

const Sandbox = () => {

return (
<div>
<RenderHtml
Title="This is the title"
        Description="This is the description">
<Example message="Hello World" />
        <h1>Render somthing here</h1>
</RenderHtml>
</div>

 );
};

export default Sandbox;

下面是RenderHtml组件的代码

const MyCard = styled(Card)();
const RenderHtml = (props: any) => {
return (
<MyCard>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          flexDirection: "column",
        }}
      >
<Typography variant="h1" sx={{ textAlign: "center" }}>
{props.Title}
        </Typography>
<Typography variant="subtitle1" sx={{ textAlign: "center" }}>
 {props.Description}
        </Typography>
      </div>
    </MyCard>
  );
};

export default RenderHtml;

我浏览了不同的示例和教程,无法理解如何渲染。如果有人可以帮助我解决这个问题。

【问题讨论】:

  • &lt;RenderHtml&gt; 里面的东西没有渲染吗?如果是这样,你能告诉我们RenderHtml的代码吗?
  • @NicholasTower 我编辑了我的问题,包括

标签: reactjs typescript components render


【解决方案1】:

如果你想像这样渲染里面的内容,你必须将 {props.children} 添加到组件中:

对于组件 1

const Test=(props)=>{
    return <>
    {props.children}
    </>
}

对于组件2

const Test2=(props)=>{
    return <>
    {props.children}
    </>
}

对于 App.js

   <Test>
     <Test2>
       asd
     </Test2>
   </Test>

【讨论】:

  • 感谢它的工作!
【解决方案2】:

当您在另一个组件中渲染组件时,这些组件会作为 prop children 传递给外部组件。要使内部组件产生任何效果,外部组件需要对 children 属性做一些事情,而您的 RenderHtml 组件目前还没有这样做。

例如,如果您希望子项在标题之后但在 div 内呈现,您可以这样做:

const RenderHtml = (props: any) => {
  return (
    <MyCard>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          flexDirection: "column",
        }}
      >
        <Typography variant="h1" sx={{ textAlign: "center" }}>
          {props.Title}
        </Typography>
        <Typography variant="subtitle1" sx={{ textAlign: "center" }}>
          {props.Description}
        </Typography>
        {props.children}
      </div>
    </MyCard>
  );
};

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 2020-09-04
    • 2019-04-19
    • 2018-12-12
    • 2018-08-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多