如何通过条件渲染修改已创建样式组件的单个属性
解决方法:仅修改现有样式的单个属性
你当前的写法{styles.backgroundColor:'red'}是无效的对象语法,要实现仅覆盖原有样式里的backgroundColor属性,可以用对象扩展运算符来合并样式:
直接在JSX中处理
把原有样式展开后,再重新定义要修改的属性,新属性会覆盖原有值:
function App() { // 注意:你代码里定义的state是message,但使用了notification,建议统一变量名 const [notification, setNotification] = useState(false); const styles = { backgroundColor:'lightGray', // 其他样式属性... } return ( <div> <h1 style={notification ? styles : { ...styles, backgroundColor: 'red' }}>Test</h1> </div> ) }
抽成变量(更清晰的写法)
如果样式逻辑复杂,可以提前计算最终样式,让JSX代码更简洁:
function App() { const [notification, setNotification] = useState(false); const styles = { backgroundColor:'lightGray', // 其他样式属性... } // 计算最终要应用的样式 const headingStyles = notification ? styles : { ...styles, backgroundColor: 'red' }; return ( <div> <h1 style={headingStyles}>Test</h1> </div> ) }
原理:...styles会把原有样式对象的所有属性复制到新对象中,之后的backgroundColor: 'red'会覆盖原有对象里的同名属性,这样就只修改了目标属性,其他样式保持不变。
内容的提问来源于stack exchange,提问作者user9561062
相关产品推荐
相关产品推荐

