当前位置:首页 > React

react如何使用插槽

2026-02-26 16:05:03React

使用 props.children 实现基础插槽

在 React 中,插槽的核心是通过 props.children 传递子组件。父组件可以通过嵌套子元素的方式将内容传递给子组件,子组件通过 props.children 接收并渲染。

父组件示例:

<ParentComponent>
  <div>这是插槽内容</div>
</ParentComponent>

子组件示例:

function ParentComponent(props) {
  return <div>{props.children}</div>;
}

命名插槽(通过 props 传递)

如果需要多个插槽(类似 Vue 的具名插槽),可以通过传递特定 props 实现。父组件将不同内容分配到不同的 props,子组件按需渲染。

父组件示例:

<Modal
  header={<h1>标题</h1>}
  body={<p>正文内容</p>}
  footer={<button>关闭</button>}
/>

子组件示例:

function Modal(props) {
  return (
    <div>
      <div className="header">{props.header}</div>
      <div className="body">{props.body}</div>
      <div className="footer">{props.footer}</div>
    </div>
  );
}

使用 React.cloneElement 动态控制插槽

通过 React.cloneElement 可以向插槽内容注入额外的 props 或修改行为。适用于需要动态控制子组件的场景。

示例:

function Tabs(props) {
  const [activeIndex, setActiveIndex] = useState(0);
  return (
    <div>
      {React.Children.map(props.children, (child, index) =>
        React.cloneElement(child, {
          isActive: index === activeIndex,
          onClick: () => setActiveIndex(index),
        })
      )}
    </div>
  );
}

使用 Context 跨层级传递插槽内容

对于深层嵌套的组件,可以通过 Context 共享插槽内容,避免逐层传递 props

示例:

const SlotContext = React.createContext();

function Layout() {
  return (
    <SlotContext.Provider value={{ header: <Header />, footer: <Footer /> }}>
      <Page />
    </SlotContext.Provider>
  );
}

function Page() {
  const { header, footer } = useContext(SlotContext);
  return (
    <div>
      {header}
      <main>页面内容</main>
      {footer}
    </div>
  );
}

使用 render props 实现灵活插槽

通过函数类型的 props,父组件可以动态决定插槽内容的渲染逻辑。

示例:

react如何使用插槽

function DataFetcher({ render }) {
  const [data, setData] = useState(null);
  useEffect(() => {
    fetchData().then(setData);
  }, []);

  return <div>{render(data)}</div>;
}

// 使用方式
<DataFetcher render={(data) => (data ? <p>{data}</p> : <p>加载中...</p>)} />

注意事项

  • props.children 可以是任意类型(字符串、数组、组件等),需处理边界情况(如 null)。
  • 命名插槽更适合复杂布局,但需避免过度设计。
  • Context 适用于全局共享插槽,但可能增加组件耦合性。
  • render props 适合逻辑复用,但嵌套过深会影响可读性。

分享给朋友:

相关文章

react路由如何使用

react路由如何使用

React 路由的基本使用 React 路由通常通过 react-router-dom 库实现,用于管理单页面应用(SPA)中的页面导航。 安装 react-router-dom: npm ins…

vue插槽的实现原理

vue插槽的实现原理

Vue插槽的基本概念 插槽(Slot)是Vue组件化开发中的重要特性,允许父组件向子组件传递模板片段,实现内容分发。插槽的核心目的是增强组件的灵活性和复用性,通过占位符机制将父组件的内容注入到子组件的…

react激光如何使用

react激光如何使用

安装React激光库 在项目中安装React激光库,通常通过npm或yarn完成。确保项目已初始化并具备React环境。 npm install react-laser-beam # 或 yar…

react如何使用less

react如何使用less

使用 Less 在 React 项目中 要在 React 项目中使用 Less,需要安装相关依赖并配置构建工具(如 Webpack 或 Create React App 的配置覆盖)。以下是具体方法:…

react如何使用插槽

react如何使用插槽

使用props.children实现基础插槽 React中插槽的核心是通过props.children传递子组件。父组件在标签内部放置的内容会自动成为children属性: // 父组件 <C…

react中如何使用swiper

react中如何使用swiper

安装 Swiper 依赖 在 React 项目中使用 Swiper 需要安装 Swiper 的核心库和 React 组件库。通过 npm 或 yarn 安装以下依赖: npm install swi…