【问题标题】:Css transition does not work for the first run in ReactCss 过渡不适用于 React 中的第一次运行
【发布时间】:2020-09-17 13:24:08
【问题描述】:

我做了一个进度条组件:

import React, {useState, useEffect} from "react";

var ProgressBar = ({percentage, duration}) => {
    
let [style, setStyle] = useState({
    "position":"relative"
})
useEffect(()=>{
        setStyle({
            "top":"0px",
            "position":"relative",
            "height":"100%",
            "backgroundColor": "lightblue",
            "color": "lightgrey",
            "left": "0px",
            "transition": `width ${duration}s`,
            "width": percentage+"%"
        });
}, [])
var cntStyle = {
    "display": "block",
    "width": "150px",
    "left":"0px",
    "backgroundColor":"grey",
    "height":"15px",
    "position": "relative"
}

    return (
        <div className="progressbar-container" 
        style={cntStyle}>
            <div className="progress" style={style}></div>
        </div>
    );
}

export default ProgressBar;

并像使用它

<ProgressBar 
    percentage="80" 
    duration="5"  />

我想知道为什么过渡不起作用。直接显示80%的进度条。

【问题讨论】:

  • 你能提供一个minimum reproducible example吗?
  • 另外,在 useEffect 第二个参数(数组)中,传递百分比,以便在它发生变化时触发

标签: css transition


【解决方案1】:

这不起作用,因为没有要转换的宽度的初始值。

“CSS 过渡允许您在给定的持续时间内平滑地更改属性值。” 阅读更多 here

如果您将百分比从一个值 (0) 更改为另一个值 (80),则此转换应该有效。

解决方法是使用间隔更新组件属性或使用进度条宽度值 0 初始化组件样式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 2021-01-29
    • 2021-07-04
    • 2015-01-02
    • 2015-11-01
    • 1970-01-01
    • 2021-08-09
    • 2019-02-09
    相关资源
    最近更新 更多