首页 > 解决方案 > 在 TypeScript 中为 Animated.View 使用 createRef 时如何创建类型

问题描述

在 React Native 组件中创建 ref 时,如果您没有提供正确的类型,Typescript 会抱怨它。

image = React.createRef();

state = {
    x: new Animated.Value(0),
    y: new Animated.Value(0),
};

render() {
    const {x, y} = this.state;
    const imageStyle = {left: x, top: y};

    return (
        <Animated.View
            ref={this.image} // I got warning message here
            {...this.responder}
            style={[styles.draggable, imageStyle]}>
            {this.props.children}
        </Animated.View>
    )
}

const styles = StyleSheet.create({
    draggable: {
    position: 'absolute',
    height: itemWidth,
    width: itemWidth,
    },  
});

我收到了这个警告

输入'{孩子:ReactNode; 样式:({左:值;顶部:值;} | {位置:“绝对”;高度:数字;宽度:数字;})[];当前:未知;参考:参考对象;}' 不可分配给类型 'IntrinsicAttributes & AnimatedProps & { children?: ReactNode; }'。类型'IntrinsicAttributes & AnimatedProps & { children?: ReactNode; 上不存在属性'ref' }'

createRef线需要像 image = React.createRef<some_type>(); 但我不知道如何创建这个some_type

标签: typescriptreact-native

解决方案


更新@types/react-native版本解决了这个问题。

"@types/react-native": "^0.61.15", -> "@types/react-native": "^0.63.37",

推荐阅读