在 React 中组合多个内联样式对象
使用扩展语法在 React 中组合多个内联样式对象,例如 style={{...style1, ...style2}}
。 扩展语法会将对象的键值对解包为最终对象,并且样式将应用于元素。
export default function App() {
const style1 = {backgroundColor: 'salmon'};
const style2 = {fontSize: '2rem'};
return (
<div>
<div style={{...style1, ...style2}}>Some content here</div>
</div>
);
}
我们使用扩展语法 ...
在 React 中组合多个内联样式对象。
我们可以根据需要合并尽可能多的内联样式对象。
export default function App() {
const style1 = {backgroundColor: 'salmon'};
const style2 = {fontSize: '2rem'};
const style3 = {color: 'white'};
return (
<div>
<div style={{...style1, ...style2, ...style3}}>Some content here</div>
</div>
);
}
在组合样式对象后,我们还可以内联添加键值对。
export default function App() {
const style1 = {backgroundColor: 'salmon'};
const style2 = {fontSize: '2rem'};
return (
<div>
<div style={{...style1, ...style2, color: 'white', padding: '2rem'}}>
Some content here
</div>
</div>
);
}
考虑扩展语法 ...
的一种简单方法是,我们将对象的键值对解包到一个新对象中。
请注意
,我们为style
道具使用了 2 组花括号。 外面的花括号组标志着将要计算的表达式的开始。
内部的花括号组是包含样式和值的对象。
请务必注意,使用扩展语法组合样式对象的顺序很重要。
export default function App() {
const style1 = {backgroundColor: 'salmon'};
const style2 = {fontSize: '2rem'};
const style3 = {backgroundColor: 'blue'}; // 👈️ overrides style1
return (
<div>
<div style={{...style1, ...style2, ...style3}}>Some content here</div>
</div>
);
}
请注意
,对象 style1 和 style3 将backgroundColor
属性设置为不同的值。
如果两个对象具有相同的键,则其属性稍后解包的对象将获胜。
这两个对象都有 backgroundColor 属性,但是 style3 的键稍后会解包,因此它的值会覆盖 style1 中的 backgroundColor 属性的值。
我们可能还会在网上看到使用 Object.assign
方法组合内联样式对象的示例。
export default function App() {
const style1 = {backgroundColor: 'salmon'};
const style2 = {fontSize: '2rem'};
return (
<div>
<div style={Object.assign({}, style1, style2, {color: 'white'})}>
Some content here
</div>
</div>
);
}
Object.assign()
方法采用的第一个参数是目标对象——源对象的属性应用到的对象。
方法采用的下一个参数是一个或多个源对象。
目标对象的属性被参数顺序中具有相同属性的其他对象覆盖。
export default function App() {
const style1 = {backgroundColor: 'salmon'};
const style2 = {fontSize: '2rem'};
return (
<div>
<div style={Object.assign({}, style1, style2, {backgroundColor: 'lime'})}>
Some content here
</div>
</div>
);
}
此行为与扩展语法 ...
一致。
这两种方法中的任何一种都有效,但我会坚持使用扩展语法 ...
,因为我发现它更易于阅读并且在 React.js 应用程序中更常用。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。