1

我试图实现与svg 路径动画的react-spring文档中所示相同的示例,但它会立即呈现:这是我的代码:

<Spring from={{ x: 0 }} to={{ x: 100 }}>
  {props => (
    <svg strokeDashoffset={props.x}>
      <path d="M7 2v11h3v9l7-12h-4l4-8z" />
    </svg>
  )}
</Spring>

这是我的代码框: https ://codesandbox.io/s/9llxp0zx8o

Svg 路径没有像这里的示例 2 那样按预期设置动画:http ://react-spring.surge.sh/spring

我想我在这里遗漏了一些东西。如果有人能找到问题并引导我,我会很高兴。

4

2 回答 2

1

要像示例中那样对其进行动画处理,您还需要将 strokeDasharray 值设置为 SVG 路径的长度。这是一个参考示例:https ://www.w3schools.com/howto/howto_js_scrolldrawing.asp

于 2019-08-28T14:21:09.873 回答
0

在此处输入图像描述

import { useEffect, useRef, useState } from 'react'
import { useSpring } from '@react-spring/core'
import { animated } from '@react-spring/web'

export const CirclePath = () => {
  const circleRef = useRef()
  const [offset, setOffset] = useState(null)
  useEffect(() => setOffset(circleRef.current.getTotalLength()), [offset])
  const config = useSpring({
    from: { offset },
    to: { offset: 0 },
  })

  return (
    <svg>
      <animated.circle
        ref={circleRef}
        cx='50'
        cy='50'
        r='30'
        strokeDashoffset={config.offset}
        strokeDasharray={offset}
        stroke='black'
        strokeWidth='2'
        fill='none'
      ></animated.circle>
    </svg>
  )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

于 2021-05-30T11:38:23.760 回答