同时解构和传入完整对象

IT技术 javascript reactjs ecmascript-6
2021-05-23 07:19:58

我有一个简单的 React 组件:

const FullContainer = ({
  backgroundColor,
  children,
}) => (
  <Container
    backgroundColor={backgroundColor}
  >
    {children}
  </Container>
);

我目前正在破坏我希望我的组件使用的仅有的两个属性,但我也想传入 props 并将其传播:

const FullContainer = (props, {
  backgroundColor,
  children,
}) => (
  <Container
    backgroundColor={backgroundColor}
    {...props}
  >
    {children}
  </Container>
);

奇怪的是,这打破了我的页面,没有错误。我一定做错了什么。我的语法错了吗?

1个回答

您可以利用rest spread syntax 它提供的剩余属性不会被解构为数组,例如

const FullContainer = ({
  backgroundColor,
  children,
  ...props
}) => (
  <Container
    backgroundColor={backgroundColor}
    {...props}
  >
    {children}
  </Container>
);