Javascript 如何提取和组合内联css样式属性
我读了几个答案,所有的答案似乎都假设你有一个包含Javascript 如何提取和组合内联css样式属性,javascript,css,reactjs,Javascript,Css,Reactjs,我读了几个答案,所有的答案似乎都假设你有一个包含CSS的单一对象,而不是单一属性,我尝试了答案,但无法实现,我想知道哪里不对,最好的方法是什么,以下是我到目前为止所做的: import React from 'react'; import FormLabel from '@material-ui/core/FormLabel'; const label = (props) => { // <label onClick={props.onClick} className={p
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;
首先,从道具对象中删除东西将是反模式的,或者至少据我所知是不好的做法 如果您只需要在此处使用的两个属性,则可以使用以下代码:
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>
)
}
const标签=(道具)=>{
让divStyle={
背景:道具背景,
textAlign:props.textAlign,
};
常量自定义样式={
宽度:“100%”
}
返回(
{props.label}
)
}
props.background或textAlign
可能未定义,这会导致问题吗?不会,因为这两个属性将在divStyle对象中设置为未定义,然后在div元素的style prop中被忽略,因为它们未设置。抱歉,我没有机会尽快尝试您的答案,我今天做了,它似乎不正常工作,我用我写的新代码更新了问题,请看一看,看看有什么问题,谢谢。你能检查一下update01
,看看为什么你的答案不起作用吗?如果你能这样做,我将非常感激,我也会接受你的答案,谢谢。就我而言,更新01中的代码应该可以工作,但也可能存在css卸载问题。如果为周围的div设置背景色,则表单标签将获得相同的背景色(如果未为其设置背景色)。
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>
)
}