reactjs - react-spring interpolate 函数不适用于 typescript

标签 reactjs typescript react-spring

我决定在我的 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>
    );
}


一切正常。

typescript 后:

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>
    );
}


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

最佳答案

一个有点老的问题,但也许有人可能需要更好的解决方案。
尝试使用 Stas Krul 提到的插值函数。但您不必分开属性 x 和 y。

const trans = (x: number, y: number) => `translate3d(${xy[0] / 10}px,${xy[1] / 10}px,0)`

const Card = () => {
const [props, set] = useSpring<{ xy: number[] }>(() => (
    {
        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: interpolate(props.xy, trans)}}
        />
    </div>
);
}

关于reactjs - react-spring interpolate 函数不适用于 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56530295/

相关文章:

javascript - useState 是同步的吗?

reactjs - 在 dockerfile 中传递环境变量

javascript - Rxjs : prevent pushing data to subjects from outisde the service

typescript - 找不到模块 'rxjs/subject/BehaviorSubject'

javascript - React-spring:包含动画图像的动画 div

javascript - 有没有办法在以下上下文中伪造 React JS 中的循环动画?

javascript - 根据窗口大小更改 Prop 值

javascript - 使用 axios POST 请求更新 JSON

javascript - 如何使用相同的 Restful 后端在两个独立的网络应用程序(javascript)之间进行通信?

class - TypeScript - 将类存储为 map 值?