简体   繁体   English

React.js:如何使内联样式自动更新状态更改的进度条

[英]React.js: how to make inline styles automatically update progress bar on state change

I have a progress bar that I am building in React.js and Zurb Foundation that I would like to reflect the current state. 我有一个我在React.js和Zurb Foundation建立的进度条,我想反映当前的状态。 I understand that in the beginning I can set the width with something like this: 我知道在开始时我可以用这样的东西设置宽度:

render: function() {
    var spanPercent = (this.props.a - this.props.b)/this.props.a + '%';
    var spanStyle = {
        width: spanPercent
    };
    return (
        <div className="progress">
            <span className="meter" style={spanStyle}></span>
        </div>
    );
}

however, when the value of props changes due to a state change, the inline style doesn't update even though the props value changes. 但是,当props的值因状态更改而发生更改时,即使props值发生更改,内联样式也不会更新。 Is there a best practice for doing this, such as using a callback, or placing the code somewhere else? 这样做是否有最佳实践,例如使用回调或将代码放在其他位置? I would appreciate any help! 我将不胜感激任何帮助!

One solution is to put a key of the percentage on the element you want to update. 一种解决方案是在要更新的元素上放置百分比的键。 That way when react checks to see what in the DOM has changed it sees that the key has changed and thus will rebuild the DOM for the element. 这样当反应检查以查看DOM中的内容已更改时,它会发现密钥已更改,因此将重建元素的DOM。

See example below: 见下面的例子:

render: function() {
   var spanPercent = (this.props.a - this.props.b)/this.props.a + '%';
   var spanStyle = {
          width: spanPercent
       };
   return (
      <div className="progress">
        <span key={spanPercent} className="meter" style={spanStyle}></span>
      </div>
);

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM