首页 > 解决方案 > react-spring interpolate 函数不适用于打字稿

问题描述

我决定在我的 React js 应用程序中引入 TypeScript。

使用 react-spring 进行坐标插值的组件存在问题。

在 TypeScript 之前,我的组件是这样的:


function Card() {
    const [props, set] = useSpring(() => (
        {
            xy: [0, 0],
            config: {mass: 10, tension: 550, friction: 140}
        }));

    const calc = (x, y) => [x - window.innerWidth / 2, y - window.innerHeight / 2]

    return (
        <div onMouseMove={({clientX: x, clientY: y}) => set({xy: calc(x, y)})}>
            <animated.div className="card1" style={{transform: props.xy.interpolate((x,y) => `translate3d(${x / 10}px,${y / 10}px,0)`)}}/>
        </div>
    );
}

一切正常。

打字稿后:


function Card() {
    const [props, set] = useSpring(() => (
        {
            xy: [0, 0],
            config: {mass: 10, tension: 550, friction: 140}
        }));

    const calc = (x: number, y: number) => [x - window.innerWidth / 2, y - window.innerHeight / 2]

    return (
        <div onMouseMove={({clientX: x, clientY: y}) => set({xy: calc(x, y)})}>
            <animated.div className="card1" style={{transform: props.xy.interpolate((xy) => `translate3d(${xy[0] / 10}px,${xy[1] / 10}px,0)`)}}/>
        </div>
    );
}

它不起作用,我没有编译错误,根本没有发生翻译。“样式”不会注入到元素中。

标签: reactjstypescriptreact-spring

解决方案


对我来说,以前的答案都没有帮助解决这个问题。

深入探索该库,我在声明文件 ( node_modules/@react-spring/core/index.d.ts) 中发现了以下几行:

/** Map the value of one or more dependencies */
declare const to: Interpolator;
/** @deprecated Use the `to` export instead */
declare const interpolate: Interpolator;

所以本质上interpolate,你现在应该使用 ,而不是使用to,如下所示:

import { to } from "react-spring"

<animated.div style={{ transform: to(props.xy, trans) }} />

推荐阅读