带有 react-spring 的打字稿。 属性 'interpolate' 在类型 'number' 上不存在
Typescript with react-spring. Property 'interpolate' does not exists on type 'number'
我将 react-spring 与 Typescript 一起使用。当我将本机渲染与 react-spring 一起使用时,我收到一条错误消息给插值函数。
"Property 'interpolate' does not exist on type 'number'"
我尝试为Spring组件内部props引入一个接口,但我无法摆脱各种错误信息。
import * as React from 'react';
import { FC, useState } from 'react';
import { Spring, animated as a } from 'react-spring/renderprops';
interface Props {
onClick: Function;
}
/*interface SpringProps {
scale: number | Scale;
}
interface Scale {
interpolate: Function;
}*/
const SpringButton: FC<Props> = ({ onClick }) => {
const [pressed, setPressed] = useState(false);
return (
<Spring native from={{ scale: 1 }} to={{ scale: pressed ? 0.8 : 1 }}>
{(props /*: SpringProps*/) => (
<a.button
style={{
height: '100px',
width: '100px',
transform: props.scale.interpolate(scale => `scale(${scale})`)
}}
onMouseDown={() => setPressed(true)}
onClick={e => {
setPressed(false);
onClick(e);
}}
onMouseLeave={() => setPressed(false)}
>
Click me
</a.button>
)}
</Spring>
);
};
export default SpringButton;
原因
当使用 render-props 版本的 react-spring 时,插值的使用与 hooks 版本略有不同。 interpolate
在 scale
上不存在,因为 scale
只是一个普通的旧数字,而不是对象。
修复
您需要先导入插值:
import { interpolate, Spring, animated as a } from 'react-spring/renderprops';
然后使用导入的函数设置按钮样式:
style={{
height: '100px',
width: '100px',
transform: interpolate(
[props.scale],
(s) => `scale(${s})`
),
}}
我将 react-spring 与 Typescript 一起使用。当我将本机渲染与 react-spring 一起使用时,我收到一条错误消息给插值函数。
"Property 'interpolate' does not exist on type 'number'"
我尝试为Spring组件内部props引入一个接口,但我无法摆脱各种错误信息。
import * as React from 'react';
import { FC, useState } from 'react';
import { Spring, animated as a } from 'react-spring/renderprops';
interface Props {
onClick: Function;
}
/*interface SpringProps {
scale: number | Scale;
}
interface Scale {
interpolate: Function;
}*/
const SpringButton: FC<Props> = ({ onClick }) => {
const [pressed, setPressed] = useState(false);
return (
<Spring native from={{ scale: 1 }} to={{ scale: pressed ? 0.8 : 1 }}>
{(props /*: SpringProps*/) => (
<a.button
style={{
height: '100px',
width: '100px',
transform: props.scale.interpolate(scale => `scale(${scale})`)
}}
onMouseDown={() => setPressed(true)}
onClick={e => {
setPressed(false);
onClick(e);
}}
onMouseLeave={() => setPressed(false)}
>
Click me
</a.button>
)}
</Spring>
);
};
export default SpringButton;
原因
当使用 render-props 版本的 react-spring 时,插值的使用与 hooks 版本略有不同。 interpolate
在 scale
上不存在,因为 scale
只是一个普通的旧数字,而不是对象。
修复
您需要先导入插值:
import { interpolate, Spring, animated as a } from 'react-spring/renderprops';
然后使用导入的函数设置按钮样式:
style={{
height: '100px',
width: '100px',
transform: interpolate(
[props.scale],
(s) => `scale(${s})`
),
}}