在React 18中,实现插槽(slots)的功能主要有以下两种方式:
1. 使用 props.children
子组件(MyComponent.js)
import React from 'react';
function MyComponent(props) {
return (
<div>
<h2>我是子组件</h2>
{props.children} {/* 渲染插槽内容 */}
</div>
);
}
export default MyComponent;
父组件(App.js)
import React from 'react';
import MyComponent from './MyComponent';
function App() {
return (
<MyComponent>
<p>这是插入到插槽的内容</p>
</MyComponent>
);
}
export default App;
2. 使用具名插槽(通过 props 传递)
子组件(MyComponent.js)
import React from 'react';
function MyComponent(props) {
return (
<div>
<h2>我是子组件</h2>
<header>{props.headerSlot}</header> {/* 渲染头部插槽 */}
<main>{props.mainSlot}</main> {/* 渲染主体插槽 */}
<footer>{props.footerSlot}</footer> {/* 渲染底部插槽 */}
</div>
);
}
export default MyComponent;
父组件(App.js)
import React from 'react';
import MyComponent from './MyComponent';
function App() {
return (
<MyComponent
headerSlot={<h1>这是头部插槽的内容</h1>}
mainSlot={<p>这是主体插槽的内容</p>}
footerSlot={<p>这是底部插槽的内容</p>}
/>
);
}
export default App;
3. 作用域插槽(传递数据给插槽)
子组件(MyComponent.js)
import React from 'react';
function MyComponent(props) {
const data = { name: 'Alice', age: 30 };
return (
<div>
<h2>我是子组件</h2>
{props.scopeSlot(data)} {/* 传递数据给作用域插槽 */}
</div>
);
}
export default MyComponent;
父组件(App.js)
import React from 'react';
import MyComponent from './MyComponent';
function App() {
function renderScopeSlot(data) {
return <p>用户:{data.name},年龄:{data.age}</p>;
}
return (
<MyComponent scopeSlot={renderScopeSlot} />
);
}
export default App;
注意事项
props.children:适用于渲染单个或多个子节点,作为默认插槽使用。- 具名插槽:通过特定的
prop名称传递 JSX 元素,实现更灵活的插槽命名。 - 作用域插槽:子组件通过函数参数将数据传递给父组件提供的插槽函数,父组件在插槽中接收并使用这些数据。
以上方法可以帮助你在 React 18 中实现类似 Vue 的插槽功能,提升组件的复用性和灵活性。
前端工程师、程序员

浙公网安备 33010602011771号