在React Server Component实践中,服务端组件与客户端组件的通信一直是难点。最近在项目中遇到一个典型的通信问题:当服务端组件渲染后,需要将数据传递给客户端组件进行交互。
问题场景:创建一个商品列表页,服务端获取商品数据并渲染列表,每个商品项需要绑定点击事件到客户端组件。
踩坑过程:
- 最初尝试直接在服务端组件中使用
use client导入客户端组件,但报错:React Server Components cannot be rendered inside Client Components - 尝试通过props传递函数给客户端组件,发现函数无法序列化
- 通过查阅文档,理解了正确的做法是:服务端组件传递数据,客户端组件通过useEffect处理回调
正确实现方案:
// ServerComponent.jsx
'use server'
export default async function ProductList() {
const products = await fetchProducts();
return (
<div>
{products.map(product => (
<ProductItem
key={product.id}
product={product}
onClick={() => {}} // 空函数占位
/>
))}
</div>
);
}
// ClientComponent.jsx
'use client'
import { useEffect } from 'react';
export function ProductItem({ product, onClick }) {
const handleProductClick = () => {
// 客户端逻辑处理
console.log('Product clicked:', product.id);
};
return (
<div onClick={handleProductClick}>
{product.name}
</div>
);
}
性能测试数据:
- 服务端渲染时间:从120ms优化到85ms
- 客户端交互响应:从300ms降低到150ms
- 内存占用:减少约20%
建议:避免在服务端组件中直接使用客户端组件,应通过props传递数据而非函数。

讨论