数字滚动组件(react)

基于react实现一个数字滚动组件(vue也一样,逻辑相同)

直接上代码

1.number-roll.tsx
interface NumberRollProps {
  value: number;
}
const NUMBER_LIST = Array.from(new Array(10).keys());
const SCROLL_HEIGHT = -15; // 数字滚动高度(也就是数字字体大小),可根据字体大小修改
const NumberRoll = (props: NumberRollProps) => {
  const { value } = props;
  const style = {
    top: `${SCROLL_HEIGHT * value}px`,
  };
  return (
    <div className="number-animation-wrap">
      <div className="number-animation-wrap-hidden">0</div>
      <div className="number-animation" style={style}>
        {NUMBER_LIST.map((item, index) => (
          <div className="number" key={index}>
            {item}
          </div>
        ))}
      </div>
    </div>
  );
};
export default memo(NumberRoll);
2.number-roll.scss
.number-animation-wrap {
    position: relative;
    display: inline-block;
    overflow: hidden;

    .number-animation {
        position: absolute;
        left: 0;
        top: 0;
        height: auto;
        transform-origin: 0 0;
        transition: top 0.4s;  // 可调整滚动速度
    }

    .number, .number-animation-wrap-hidden {
        font-size: 15px;    // 数字滚动高度
        line-height: 15px;
        height: 15px;
        font-weight: 400;
        text-align: center;
    }

    .number-animation-wrap-hidden{
        visibility: hidden;
    }
}
3.使用组件的方式
import NumberRoll from './number-roll.tsx';
const [number,setNumber] = useState(0);
number?.toString()?.split('')?.map((numberItem, index) => (
	<NumberRoll key={index} value={Number(numberItem)} />
))
// 在number改变时调用setNumber更新state,就能看到数字滚动的动画了

完毕!

你可能感兴趣的:(经验分享,react.js,javascript,前端)