如何解决如何将多个内联样式作为道具应用于组件?
我尝试了很多不同的东西,但没有任何效果。它要么破坏应用程序,要么只应用一种样式,但不能同时应用两种样式。我有一个父组件将一些样式传递给子组件,然后子组件本身也有一些本地样式。
父组件:
<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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。