常州市金坛建设局网站,wordpress 移动端不显示图片,什么是网络营销的特点,建设网站学什么条件目录 通过 children 属性结合条件渲染通过 children 和 slot 属性实现具名插槽通过 props 实现具名插槽 在 React 中#xff0c;并没有直接类似于 Vue 中的“插槽”机制#xff08;slot#xff09;。但是#xff0c;React 可以通过
props和
children 来实现类似插槽的功能… 目录 通过 children 属性结合条件渲染通过 children 和 slot 属性实现具名插槽通过 props 实现具名插槽 在 React 中并没有直接类似于 Vue 中的“插槽”机制slot。但是React 可以通过
props和
children 来实现类似插槽的功能允许你将组件的内容进行灵活插入和替换。 通过 children 属性结合条件渲染
通过 children 来传递任意数量的子元素然后在组件内部通过位置进行条件渲染从而实现插槽功能。
Layout 组件通过 children 渲染传递给它的所有子元素而这些子元素可以是任何内容类似于 Vue 中的默认插槽。虽然在某些情况下children 已经是一个数组例如多个子元素的情况但 React.Children.toArray 会确保你始终获得一个标准化的数组过滤掉null、undefined等数据。
//子组件
const Layout ({ children }) {children React.Children.toArray(children);console.log(children,children)return (div classNamelayoutheaderHeader/headermain{children}/main {/* 这里的 children 就是父组件传递进来的内容 */}footerFooter/footer/div);
};
//父组件
const App () {return (Layouth1Hello, React!/h1pThis is the main content of the page./p/Layout);
};打印出children就是父组件标签里内容编译成的virtualDOM。 通过 children 和 slot 属性实现具名插槽
在标签上加slot来标记标签
//父组件
root.render(DemoOne titleREACT好好玩哦 x{10}span slotfooter我是页脚/spanspan哈哈哈哈/spanspan slotheader我是页眉/span/DemoOne/
); 子组件根据children属性中的slot来区分插槽
//子组件
const DemoOne function DemoOne(props) {let { title, x, children } props;children React.Children.toArray(children);let headerSlot [],footerSlot [],defaultSlot [];children.forEach(child {// 传递进来的插槽信息都是编译为virtualDOM后传递进来的「而不是传递的标签」let { slot } child.props;if (slot header) {headerSlot.push(child);} else if (slot footer) {footerSlot.push(child);} else {defaultSlot.push(child);}});return div classNamedemo-box{headerSlot}br /h2 classNametitle{title}/h2span{x}/spanbr /{footerSlot}/div;
};
通过 props 实现具名插槽
显式传递 props 来模拟具名插槽传递不同的内容到特定的插槽位置
const DemoOne ({ title, x, children, footer, header }) {return (div classNamedemo-boxh1{title}/h1div{header}/div {/* 渲染具名插槽 header */}div{children}/div {/* 渲染默认插槽 */}div{footer}/div {/* 渲染具名插槽 footer */}/div);
};const App () {return (DemoOne titleREACT好好玩哦 x{10} footer{span我是页脚/span} header{span我是页眉/span}span哈哈哈哈/span/DemoOne);
};