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

How to apply multiple inline styles to a component as props?

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

父组件:

<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>