在 React 中将组件作为属性 props 传递

我们可以使用内置的 children 属性在 React 中将组件作为属性 props 传递。 我们在组件的开始标签和结束标签之间传递的所有元素都会分配给 children 属性。

function Center({children}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {children}
    </div>
  );
}
export default function App() {
  const CustomHeading = () => {
    return <h2>Hello world</h2>;
  };
  // ?️ pass children to the Center component
  return (
    <div>
      <Center>
        <CustomHeading />
      </Center>
    </div>
  );
}

这个例子展示了我们在组件的开始标签和结束标签之间传递的所有内容是如何分配给 React 中的 children 属性的。

该组件可以从它的 props 对象中解构 children 属性,并像我们在 Center 组件中所做的那样渲染它。或者,我们可以直接将组件作为属性传递给子组件。

// ?️ 将按钮属性重命名为 Button(大写首字母)
function Wrapper({button: Button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Button />
    </div>
  );
}
export default function App() {
  const Button = () => {
    return <button onClick={() => console.log('button clicked')}>Click</button>;
  };
  // ?️ 将button作为属性传递给 Wrapper 组件
  return (
    <div>
      <Wrapper button={Button} />
    </div>
  );
}

我们将 Button 组件作为 props 传递给 Wrapper 组件。

Wrapper 组件必须将 prop 从 button 重命名为 Button(首字母大写),因为所有组件名称都必须以大写字母开头。

如果 Button 组件接受了 props,我们可以在 Wrapper 组件中使用它时传递它们。或者,我们可以将组件作为道具传递给子组件并直接设置其属性。

function Wrapper({button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {button}
    </div>
  );
}
export default function App() {
  const Button = ({text}) => {
    return (
      <button onClick={() => console.log('button clicked')}>{text}</button>
    );
  };
  return (
    <div>
      <Wrapper button={<Button text="Some button text" />} />
    </div>
  );
}

在这个例子中,我们在传递给 Wrapper 组件时直接设置了 Button 组件的 props。

注意 ,我们没有传递实际的组件函数,而是传递 Button 组件的返回值。

这意味着我们必须将 prop 用作 {button},而不是 Wrapper 组件中的 <Button/>

我们也可以混合搭配。 这是一个传递 Button 组件的示例,该组件采用 children 属性并呈现其子项。

function Wrapper({button: Button}) {
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Button>
        <h2>一些按钮文本</h2>
      </Button>
    </div>
  );
}
export default function App() {
  const Button = ({children}) => {
    return (
      <button onClick={() => console.log('button clicked')}>{children}</button>
    );
  };
  return (
    <div>
      <Wrapper button={Button} />
    </div>
  );
}

我们在 Button 组件的开始标签和结束标签之间传递的任何内容都会被渲染。

将组件作为 props 传递时,请注意何时传递实际的函数组件,例如 button={Button} 与传递函数组件返回的内容时相比,例如 button={<Button text="一些按钮文本" />}

这很重要,因为当我们传递实际的函数组件时,它可以用作 <Button />。 另一方面,如果你传递函数的返回值,它必须用作{button}