带react-spring的打字稿。属性“ interpolate”在类型“ number”上不存在

时间:2019-03-13 09:40:51

标签: reactjs typescript react-spring

我在Typescript中使用react-spring。当我将本地渲染与react-spring一起使用时,我会向插值函数显示一条错误消息。

“类型'number'上不存在属性'interpolate'”

我试图为Spring组件内部道具引入一个接口,但是我无法摆脱各种错误消息。

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;

https://codesandbox.io/s/34zopyr8zq

1 个答案:

答案 0 :(得分:1)

为什么

当使用react-spring的render-props版本时,interpolate的使用与hooks版本略有不同。 interpolatescale上不存在,因为scale只是一个普通的旧数字,而不是一个对象。

修复

您需要先导入插值:

import { interpolate, Spring, animated as a } from 'react-spring/renderprops';

然后使用导入的功能设置按钮的样式:

style={{
  height: '100px',
  width: '100px',
  transform: interpolate(
    [props.scale],
    (s) => `scale(${s})`
  ),
}}