前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用React animated/useSpring报错​Got NaN while animating的解决方法

使用React animated/useSpring报错​Got NaN while animating的解决方法

作者头像
德顺
发布2023-08-25 13:25:13
1520
发布2023-08-25 13:25:13
举报
文章被收录于专栏:前端资源前端资源

使用 React 的 <animated.div /> 时,发现控制台一直打印报错/报警:Got NaN while animating: SpringValue {id: 2899, key: 'width', _priority: 0, animation: Animation, queue: undefined, …} 。

这说明页面中有使用数学运算,并且在计算中传递了非整数值 NaN ,这样表达式会返回 NaN ,造成报错。

报错代码示例:

代码语言:javascript
复制
import { useSpring, animated, config } from 'react-spring';

const Index: React.FC<{
  value: number;
  minValue: number;
  maxValue: number;
  maxWidth: number;
  index: number;
  barColor: string;
}> = (props) => {
  const { value, minValue, maxValue, maxWidth, index, barColor } = props;
  const barWidth = ((value - minValue) / (maxValue - minValue)) * maxWidth;
  const springProps = useSpring({
    from: { opacity: 1, width: 0, height: '100%', background: barColor },
    to: { opacity: 1, width: barWidth, height: '100%', background: barColor },
    delay: 4,
    config: config.default,
  });

  return (
    <div
      style={{
        height: '100%',
        borderRadius: 2,
      }}
    >
        <animated.div style={springProps} />
    </div>
  );
};

export default PerCentBar;

这里的 barWidth 变量可能会出现空值,给它一个默认值 0 即可。

解决方法:

12 行改为:

代码语言:javascript
复制
const barWidth = ((value - minValue) / (maxValue - minValue)) * maxWidth || 0;

未经允许不得转载:w3h5-Web前端开发资源网 » 使用React animated/useSpring报错​Got NaN while animating的解决方法

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-01-11),如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解决方法:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档