2017-09-15 92 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> 
); 
}