Skip to content

children

什么是 children

children 是一个特殊的 prop,它允许将组件作为数据传递到其他组件。

基本用法

props.children可以是任意的 JSX 元素,包括原始值、React 元素、函数、组件等。

tsx
function MyButton({ children }: { children: React.ReactNode }) {
  return <button>{children}</button>;
}

export default function ChildrenOriginalValue() {
  return <MyButton>Click My Button</MyButton>;
}
tsx
function Page({ children }: { children: React.ReactNode }) {
  return <div>{children}</div>;
}

export default function ChildrenReactElement() {
  return (
    <Page>
      <h1>标题</h1>
      <p>段落</p>
    </Page>
  );
}
tsx
function Container({
  children,
}: {
  children: (data: number[]) => React.ReactNode;
}) {
  const data = [1, 2, 3, 4, 5];
  return <div>{children(data)}</div>;
}

export default function ChildrenFunction() {
  return (
    <Container>{(data) => data.map((item) => <div>{item}</div>)}</Container>
  );
}
tsx
function Wrapper({ children }: { children: React.ReactNode }) {
  return <div>{children}</div>;
}

function Greeting({ name }: { name: string }) {
  return <p>Hello, {name}</p>;
}

export default function ChildrenComponent() {
  return (
    <Wrapper>
      <Greeting name="React" />
    </Wrapper>
  );
}

传递多个具名的子组件

tsx
function Page({
  header,
  content,
  footer,
}: {
  header: JSX.Element;
  content: JSX.Element;
  footer: JSX.Element;
}) {
  return (
    <div>
      {header}
      {content}
      {footer}
    </div>
  );
}

export default function ChildrenMultiple() {
  return (
    <Page
      header={<h1>页头</h1>}
      content={<div>页面内容</div>}
      footer={<h1>页尾</h1>}
    ></Page>
  );
}