如何将多个内联样式作为道具应用于组件?

问题描述

我尝试了很多不同的东西,但没有任何效果。它要么破坏应用程序,要么只应用一种样式,但不能同时应用两种样式。我有一个父组件将一些样式传递给子组件,然后子组件本身也有一些本地样式。

父组件:

<CardSettings headline="Media accounts" size={{ flex: 1 }}></CardSettings>

子组件 CardSettings.jsx:

const CardSettings = (props) => {
    return (
        <div style={({ background: '#fff' },props.size)}>
            <h2 style={styles.headline}>{props.headline}</h2>
            {props.children}
        </div>
    )
}

我在这里做错了什么?在这种情况下,flex: 1 会被应用,但不会 background: #fff

解决方法

考虑到您的 size 道具是一个对象,您可以使用 spread syntax 将这些样式与该 div 中已有的样式合并:

<div style={{ background: '#fff',...props.size }}>
  <h2 style={styles.headline}>{props.headline}</h2>
  {props.children}
</div>

ES6 之前的解决方案:

或者,您可以尝试 Object.assign

<div style={Object.assign({{},background: '#fff',props.size)}>
  <h2 style={styles.headline}>{props.headline}</h2>
  {props.children}
</div>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...