我读了几个答案,它们似乎都假设你有一个包含 CSS
而不是单个属性的对象,我尝试了这些答案但我无法让它工作,我是想知道出了什么问题,最好的方法是什么,这是我到目前为止所做的:
import React from 'react';
import FormLabel from '@material-ui/core/FormLabel';
const label = (props) => {
// <label onClick={props.onClick} className={props.className + ' ' + props.gridClass} style={props.inlineStyle} >{props.label}</label>
let divStyleArray = [];
if (typeof props.inlineStyle.background !== 'undefined') {
divStyleArray.push(props.inlineStyle.background)
delete props.inlineStyle.background
}
if (typeof props.inlineStyle.textAlign !== 'undefined') {
divStyleArray.push(props.inlineStyle.textAlign)
delete props.inlineStyle.textAlign
}
const customStyle = {
width: '100%'
}
const divStyle = Object.assign({}, ...divStyleArray);
return (
<div className={props.gridClass} style={{divStyle}}>
<FormLabel component="label" onClick={props.onClick} style={{ ...customStyle, ...props.inlineStyle }}>{props.label}</FormLabel>
</div>
)
}
export default label;
我的目标是提取一些 CSS
属性,将其提供给 div
,然后将其余部分提供给 div
中的内容
更新 01:
我尝试了给出的答案,但它似乎无法正常工作,这就是我所做的:
import React from 'react';
import FormLabel from '@material-ui/core/FormLabel';
const label = (props) => {
let inlineStyle = {
...props.inlineStyle
}
const divStyle = {
background: inlineStyle.background,
textAlign: inlineStyle.textAlign,
}
delete inlineStyle.background;
delete inlineStyle.textAlign;
const customStyle = {
width: '100%'
}
return (
<div className={props.gridClass} style={divStyle}>
<FormLabel component="label" onClick={props.onClick} style={{ ...customStyle, ...inlineStyle }}>{props.label}</FormLabel>
</div>
)
}
export default label;
最佳答案
首先,据我所知,从 props 对象中删除内容是反模式的,或者至少是不好的做法。
如果您只需要您在那里使用的两个属性,您可以使用此代码:
const label = (props) => {
let divStyle = {
background: props.background,
textAlign: props.textAlign,
};
const customStyle = {
width: '100%'
}
return (
<div className={props.gridClass} style={{divStyle}}>
<FormLabel
component="label"
onClick={props.onClick}
style={{
...customStyle,
...props.inlineStyle,
background: undefined,
textAlign: undefined,
}}
>{props.label}</FormLabel>
</div>
)
}
关于javascript - 我如何提取和组合内联 css 样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471946/