2017-09-15 65 views
1

我需要根据传入我的反应组件的道具来设置div的背景颜色。 React组件的内联样式我非常清楚,但我不知道如何正确应用内联样式以根据prop来更改。如果道具selected等于true,我只想在right-toggle的联机样式中分配道具rightSideColor的值。条件内联样式基于道具的反应组件

export default function UiToggle(props) { 
    const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props; 

    return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} > 
     <div className="lr-gray-background" /> 
     <div> 
     {leftLabel} 
     </div> 
     <div className={'lr-toggle right-toggle' style={{ selected ? (backgroundColor: rightSideColor) : null }}> 
     {rightLabel} 
     </div> 
    </div> 
); 
} 

回答

0

我会建议将所有样式和条件运算符放在单独的const中。

export default function UiToggle(props) { 

    const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props; 

    const rightToggleStyle = { 
    backgroundColor: selected ? rightSideColor : null 
    }; 

    return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} > 
     <div className="lr-gray-background" /> 
     <div> 
     {leftLabel} 
     </div> 
     <div className="lr-toggle right-toggle" style={rightToggleStyle}> 
     {rightLabel} 
     </div> 
    </div> 
); 
} 

我会尽量做宽度的样式。祝你好运!

0

修正了一个错字 - {之前的className

,你可以返回一个空的对象,如果选择是别人的期望值

例假:

export default function UiToggle(props) { 
    const { leftLabel, rightLabel, selected, rightSideColor, leftSideColor } = props; 

    return (
    <div className="lr-toggle-select" style={{ width: `${width}px` }} > 
     <div className="lr-gray-background" /> 
     <div> 
     {leftLabel} 
     </div> 
     <div className='lr-toggle right-toggle' style={ selected ? {backgroundColor: rightSideColor} : {} }}> 
     {rightLabel} 
     </div> 
    </div> 
); 
}