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)
我制作了一种将任何视图样式转换为可动画样式的“种类”类型。
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
我不相信有内置的解决方案。查看React Native 的类型定义,Animated 命名空间甚至没有指定 Animated 组件的类型,只是将它们保留为any:
/**\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;\nRun Code Online (Sandbox Code Playgroud)\n\n甚至 React Native 源代码(使用 FlowType)也将 props 保留为普通的 Object 类型:
\n\nclass AnimatedComponent extends React.Component<Object> {\n \xe2\x80\xa6\n}\nRun Code Online (Sandbox Code Playgroud)\n\n这可能是因为 React Native 有专门用于内部处理动画样式和props(甚至Transforms )的包装类,这使得由于抽象而精确指定类型变得更加困难。我认为你最好的选择是使用,any因为创建你自己的类型会非常乏味,而且没有什么好处。
小智 5
// 从“react-native”导入{Animated}
interface ImageComponentProps {
height: Animated.Value;
width: Animated.Value;
opacity: Animated.Value;
uri: string;
}
Run Code Online (Sandbox Code Playgroud)
这对我有用!
| 归档时间: |
|
| 查看次数: |
12785 次 |
| 最近记录: |