React+TS项目中Background包装组件内部嵌套内容无法显示问题
问题原因
React 中自定义组件的嵌套内容会默认作为 children 属性传递给组件,你的 Background 和 BackgroundView 两层组件都没有接收、传递该属性,也没有将其渲染到组件结构中,因此内部嵌套的内容不会被显示。
修复步骤
- 修改 Background 逻辑层组件,接收并传递
children给视图层:
// 带TS类型声明写法 import type { ReactNode } from 'react'; import BackgroundView from './Background.view'; interface BackgroundProps { children?: ReactNode; } const Background = ({ children }: BackgroundProps) => { return ( <BackgroundView>{children}</BackgroundView> ); }; Background.displayName = 'Background'; Background.defaultProps = {}; export default Background;
- 修改 BackgroundView 视图层组件,接收
children并渲染到容器内部:
// 带TS类型声明写法 import type { ReactNode } from 'react'; import classes from './Background.module.scss'; interface BackgroundViewProps { children?: ReactNode; } const BackgroundView = ({ children }: BackgroundViewProps) => { return ( <div className={classes['mainContainer']}>{children}</div> ); }; BackgroundView.displayName = 'Background'; BackgroundView.defaultProps = {}; export default BackgroundView;
样式补充说明
你当前的样式中.mainContainer的z-index为10,内部伪元素z-index为-1,后续如果出现嵌套内容被白色伪元素遮挡的情况,可给嵌套内容外层套一层相对定位的容器,显式设置z-index: 1即可。
内容的提问来源于stack exchange,提问作者user16657995
相关产品推荐
相关产品推荐

