同时解构和传递完整对象 [英] Destructuring and passing in full object simultaenously

查看:91
本文介绍了同时解构和传递完整对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的React组件:

I have a simple React component:

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

我目前正在破坏我期望我的组件使用的两个属性,但我也是喜欢传递道具并传播它:

I'm currently destructing the only two properties I expect my component to use, but I'd also like to pass in props and spread it in as well:

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

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

Oddly enough, this breaks my page with no errors. I must be doing something wrong. Is my syntax wrong?

推荐答案

你可以使用 rest spread syntax ,提供剩余的属性不会像#/ p>那样被解构为

You can make use of rest spread syntax that provides the remaining properties which aren't destructured as an array like

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

这篇关于同时解构和传递完整对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆