React自定义组件内部嵌套的子元素无法渲染如何解决?
问题原因
React 中所有写在组件开闭标签之间的嵌套内容,都会被自动作为 props.children 属性传入组件。你当前的 RenderHtml 组件只渲染了 Title 和 Description 两个属性,没有处理 children 内容,自然无法展示嵌套的组件和元素。
修复方案
只需要在 RenderHtml 组件你期望展示嵌套内容的位置,渲染 props.children 即可,调整后的代码如下:
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> {/* 新增children渲染,位置可以根据你的布局需求调整 */} {props.children} </div> </MyCard> ); }; export default RenderHtml;
如果需要把嵌套内容放在卡片的其他位置,调整{props.children}的书写位置即可。
内容的提问来源于stack exchange,提问作者joekevinrayan96
相关产品推荐
相关产品推荐

