Animated.View 的样式道具的打字稿定义

Ilj*_*lja 14 typescript react-native typescript-typings

我有Props接口ViewProps从 React Native扩展的组件,即:

export interface Props extends ViewProps {
  // Custom props
}
Run Code Online (Sandbox Code Playgroud)

自然地,这扩展了style道具。有一个警告,我正在使用Animated.View并具有这样的风格:

style={{
  opacity: animationCharacter.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 1]
  }),
  transform: [
    {
      scale: animationCharacter.interpolate({
        inputRange: [0, 1],
        outputRange: [1.2, 1]
      })
    }
  ]
}}
Run Code Online (Sandbox Code Playgroud)

我认为该interpolate调用与来自 的样式类型不兼容ViewProps,但AnimatedViewProps我无法扩展。

这里有解决方案还是我必须设置style: any

Ama*_*iet 13

Starting from @types/react-native v0.61.9, you can use Animated.AnimatedProps:

For exemple for the style prop:

interface Props {
  style?: Animated.AnimatedProps<StyleProp<ViewStyle>>,
}
Run Code Online (Sandbox Code Playgroud)

Or to get all props:

export interface Props extends Animated.AnimatedProps<ViewProps> {
  // Custom props
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,仅使用 Animated.AnimatedProps&lt;ViewStyle&gt;` 就解决了这个问题。 (2认同)

pie*_*e6k 8

我制作了一种将任何视图样式转换为可动画样式的“种类”类型。

type MaybeAnimated<T> = T | Animated.Value;
type AnimatedScalar = string | number;

type AnimatedStyles<T> = {
  [Key in keyof T]: T[Key] extends AnimatedScalar
    ? MaybeAnimated<T[Key]>
    : T[Key] extends Array<infer U>
    ? Array<AnimatedStyles<U>>
    : AnimatedStyles<T[Key]>
};

type ViewAnimatedStyles = AnimatedStyles<ViewStyle>;

const test: ViewAnimatedStyles = {
  transform: [
    {
      rotateY: new Animated.Value(2),
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

你会得到自动建议和动画值的工作。

限制: Animated.Value引擎盖下的定义只是一个空类,所以从技术上讲,一切都会匹配它。因此,您将能够为其分配不正确的值(例如,纯字符串而不是数字)

阅读有关推断和条件类型的更多信息:https : //www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html


Li3*_*357 5

我不相信有内置的解决方案。查看React Native 的类型定义,Animated 命名空间甚至没有指定 Animated 组件的类型,只是将它们保留为any

\n\n
/**\n * Animated variants of the basic native views. Accepts Animated.Value for\n * props and style.\n */\nexport const View: any;\nexport const Image: any;\nexport const Text: any;\nexport const ScrollView: any;\n
Run Code Online (Sandbox Code Playgroud)\n\n

甚至 React Native 源代码(使用 FlowType)也将 props 保留为普通的 Object 类型

\n\n
class AnimatedComponent extends React.Component<Object> {\n  \xe2\x80\xa6\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这可能是因为 React Native 有专门用于内部处理动画样式props(甚至Transforms )的包装类,这使得由于抽象而精确指定类型变得更加困难。我认为你最好的选择是使用,any因为创建你自己的类型会非常乏味,而且没有什么好处。

\n


小智 5

// 从“react-native”导入{Animated}

interface ImageComponentProps {
  height: Animated.Value;
  width: Animated.Value;
  opacity: Animated.Value;
  uri: string;
}
Run Code Online (Sandbox Code Playgroud)

这对我有用!