由于 React 不允许在客户端组件中导入服务器组件,一种解决方法是创建一个外部服务器组件,并在其中渲染客户端组件,并将另一个服务器组件作为子组件传递给它。没关系,但我不明白如何将多个服务器子组件传递给客户端组件,同时能够从
children
道具中提取它们并将其放置在我喜欢的任何地方。有什么想法吗?
这是不可能的:
// ServerComp.server.jsx
export default function ServerComp() {
return <div>Server component</div>
}
// ClientComp.client.jsx
import ServerComp from "./ServerComp.server"; // This is not allowed in client component
export default function ClientComp() {
<div>
<h1>Rendering Server component like this ISN'T possible</h1>
<ServerComp />
</div>
}
但是这是可能的:
...
// ClientComp.client.jsx
export default function ClientComp({children}) {
return <div>
<h1>Rendering Server component like this IS possible</h1>
{children}
</div>
}
// OuterServerComp.server.jsx
import ClientComp from "./ClientComp.client";
import ServerComp from "./ServerComp.server";
export default function OuterServerComp() {
return (
<ClientComp>
<ServerComp />
</ClientComp>
)
}
但是我该怎么做呢?
...
// ClientComp.client.jsx
export default function ClientComp({children}) {
return <div>
// Here I want to be able to extract 1st child and place it here.
// Something like this: {children[0]}
<h1>Some other content in between</h1>
<div>
// And then I want to extract and place second children here.
//Something like this: {children[1]}
</div>
</div>
}
// OuterServerComp.server.jsx
import ClientComp from "./ClientComp.client";
import ServerComp from "./ServerComp.server";
export default function OuterServerComp() {
return (
<ClientComp>
// Passing multiple server components
<ServerComp />
<ServerComp />
</ClientComp>
)
}
i passes miltiple server components inside client component :
<WrapperComponent>
<GuestProfileView id={params.id} />
<GuestImageGallary guestId={params.id} />
</WrapperComponent>
and then in wrapper component children will be array of React.ReactNode
const WrapperComponent = ({ children }: { children: React.ReactNode[] }) => {
return (
<>
{children[0]} // first server compoenent which passesed
{children[1]} //second server compoenent which had passed
</>
);
thank you :)