React Native使用d3-interpolate-path插值SVG路径出现NaN错误如何解决
问题根因
d3-interpolate-path 对插值的两个路径有严格的结构匹配要求:两条路径的SVG指令(M/L/C/V/H等)的数量、顺序、类型必须完全一一对应。你使用的两个图标路径指令结构差异过大(一个多为直线指令,一个多为贝塞尔曲线指令,总段数也不一致),插值时无法匹配到对应的参数,就会生成NaN值。
解决方案
方案1:使用兼容性更强的flubber库(推荐)
flubber是专门处理任意SVG路径插值的工具,不需要路径结构预先匹配,适配性更强,不会出现NaN问题。
操作步骤
- 安装依赖
npm install flubber # 或 yarn add flubber
- 修改代码中插值逻辑:
import React, { Component } from "react"; import Svg, { Path } from "react-native-svg"; import { interpolate } from "flubber"; // 替换原来的d3-interpolate-path引入 import { Animated, Modal } from "react-native"; const startPath = "M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"; const endPath = "M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"; export default class Animations extends Component { state = { animation: new Animated.Value(0), }; private _path: any; componentDidMount() { // 初始化flubber插值器,可通过maxSegmentLength调整平滑度 const pathInterpolate = interpolate(startPath, endPath, { maxSegmentLength: 0.5 }); this.state.animation.addListener(({ value }) => { const path = pathInterpolate(value); path && this._path.setNativeProps({ d: path }); }); Animated.loop(Animated.sequence( [Animated.timing(this.state.animation, { toValue: 1, duration: 500, useNativeDriver: false }), Animated.timing(this.state.animation, { toValue: 0, duration: 500, useNativeDriver: false }), ] )).start() } render() { return ( <Modal transparent={true}> <Animated.View style={{ flex: 1, backgroundColor: "rgba(0,0,0,0.5)", alignItems: "center", justifyContent: "center" }}> <Svg width={150} height={150} fill="#000000"> <Path d={startPath} stroke="black" ref={(path) => (this._path = path)} /> </Svg> </Animated.View> </Modal> ); } }
方案2:继续使用d3-interpolate-path,预处理路径
如果必须使用d3-interpolate-path,需要先对两条路径做标准化处理:
- 将所有相对指令(小写的c/l/v/h等)统一转换为绝对指令(大写的C/L/V/H)
- 解析两条路径的指令段,补全段数少的路径,保证两条路径的指令数量、每段的参数长度完全一致
- 预处理完成后再传给interpolatePath生成插值器
内容的提问来源于stack exchange,提问作者Rodrigo Pissinate
相关产品推荐
相关产品推荐

