我决定在我的 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/