posts/React/separate-server-component-client-logic #328
Replies: 1 comment
-
|
안녕하세요 ~ 블로그 잘 보고 있습니다! 궁금한 점이 있어서 댓글을 남겨봅니다! 작성하신 것처럼 cloneElement로 서버 컴포넌트 children을 렌더링하게 되면, 넘겨주는 prop이 undefined로 적용되고 / 부모 서버 컴포넌트의 prop에서 변화가 되지 않는 (서버에서 렌더링된 값만 적용되는) 동작을 띄는데요 ~ 작성하신 코드에서는 children이 next/Link 컴포넌트라서 가능한 건 아닐까 하고 유추됩니다. 어떻게 생각하시나요?? 예시 코드를 남겨보겠습니다! import { ClientCompo } from './ClientCompo';
import { ServerCompo } from './ServerCompo';
export default function Page() {
return (
<div>
this is server component
<p>typeof window is... {typeof window}</p>
<ClientCompo>
<ServerCompo n={9999} />
</ClientCompo>
</div>
);
}'use client';
import type { ReactElement } from 'react';
import React, { cloneElement, useState } from 'react';
export function ClientCompo({ children }: { children: ReactElement }) {
const [n, setN] = useState(0);
const child = React.Children.only(children);
return (
<div style={{ backgroundColor: 'lightgray' }}>
this is client component
<p>typeof window is... {typeof window}</p>
<br />
<hr />
<p>state n is: {n}</p>
<button onClick={() => setN((p) => p + 1)}>up</button>
<hr />
<br />
<div>
<p>this is client component's children</p>
<p>children type is: {typeof children}</p>
<br />
{cloneElement(child, { n })}
</div>
</div>
);
}interface Props {
n: number;
}
export function ServerCompo({ n }: Props) {
return (
<div style={{ backgroundColor: 'lightgreen' }}>
<p>im passing children server compo</p>
<p>typeof window is ... {typeof window}</p>
<hr />
<br />
<p>props n is: {n}</p>
<p>props n type is: {typeof n}</p>
</div>
);
}이 경우에서 state 값인 0이 초기 값이 아닌 9999가 렌더링되며 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
posts/React/separate-server-component-client-logic
React.cloneElement API를 활용해 클라이언트 로직을 서버 컴포넌트로부터 분리한 방법에 대해 다룬 포스트입니다.
https://byjuun.com/posts/React/separate-server-component-client-logic
Beta Was this translation helpful? Give feedback.
All reactions