React应用中JS对象内三元运算符的使用问题
解决React组件中动态样式不更新的问题
你的问题核心在于静态样式对象无法响应props变化——你定义的styles是组件类外部的固定对象,它只会在模块首次加载时被创建一次,哪怕render里的isZero随着props.value改变了,这个外部的styles也不会重新计算,自然没法动态更新样式。
下面给你两种可行的解决方案:
方案一:将样式计算移到render方法内部
把样式的计算逻辑放到render里,这样每次组件因为props变化重新渲染时,都会根据当前的value重新计算样式:
import React, { Component } from 'react'; import { RaisedButton } from 'material-ui'; class Button extends Component { render() { const { value } = this.props; // 直接在render里根据props计算状态 const isZero = value === 0; // 每次渲染都重新生成样式对象 const styles = { otherStyles: { minWidth: isZero ? '120px' : '60px', margin: '5px 5px 5px 0', lineHeight: isZero ? '120px' : '60px', }, }; // 记得把样式应用到按钮上 return ( <RaisedButton style={styles.otherStyles}>{value}</RaisedButton> ); } } export default Button;
方案二:抽离样式计算为单独方法(适合复杂场景)
如果样式逻辑比较复杂,单独写一个方法来计算样式会让代码更清晰,同样每次render时都会调用这个方法获取最新样式:
import React, { Component } from 'react'; import { RaisedButton } from 'material-ui'; class Button extends Component { // 专门的样式计算方法 calculateButtonStyles() { const { value } = this.props; const isZero = value === 0; return { otherStyles: { minWidth: isZero ? '120px' : '60px', margin: '5px 5px 5px 0', lineHeight: isZero ? '120px' : '60px', }, }; } render() { const styles = this.calculateButtonStyles(); const { value } = this.props; return ( <RaisedButton style={styles.otherStyles}>{value}</RaisedButton> ); } } export default Button;
额外提醒
别再用组件外部的let isZero这种变量来控制组件状态了,这种全局变量会让组件的状态变得不可预测,最好直接从props或者组件内部的state里推导需要的状态值。
内容的提问来源于stack exchange,提问作者tinker
相关产品推荐
相关产品推荐

