简体   繁体   English

将 React Native 项目中的视图引用与 typescript 关联时出现问题。 解决了

[英]Problem associating a reference to a view in a react native project with typescript. SOLVED

I have created a react-native project with the typescript template我使用 typescript 模板创建了一个 react-native 项目

npx react-native init myApp --template react-native-template-typescript

When I associate a ref to a View in a tsx file I have this error.当我将 ref 关联到 tsx 文件中的视图时,出现此错误。

No overload matches this call.没有重载匹配此调用。 Overload 1 of 2, '(props: ViewProps | Readonly): View', gave the following error.重载 1 of 2,'(props: ViewProps | Readonly): View',给出了以下错误。 Type 'MutableRefObject' is not assignable to type 'LegacyRef |类型“MutableRefObject”不可分配给类型“LegacyRef | undefined'.不明确的'。 Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error. Overload 2 of 2, '(props: ViewProps, context: any): View',给出了以下错误。 Type 'MutableRefObject' is not assignable to type 'LegacyRef |类型“MutableRefObject”不可分配给类型“LegacyRef | undefined'不明确的'

If I change the file extension from.tsx to.js the error dissapears so I suppose this is a typescript problem.如果我将文件扩展名从.tsx 更改为.js,则错误消失,所以我想这是 typescript 问题。 Please, anybody knows how to handle this?请问,有大神知道怎么处理吗?

These are the versions I'm using and a code example这些是我正在使用的版本和代码示例

import {View, Text} from 'react-native';

const Test = () => {
  const containerRef = useRef();

  return (
    <View ref={containerRef}>
      <Text>Hi</Text>
    </View>
  );
};

export default Test;
"react": "17.0.1",
"react-native": "0.64.0",
"typescript": "^3.8.3"

Thanks a lot in advance非常感谢提前

For me this solution is working, maybe is useful for anybody.对我来说,这个解决方案是有效的,也许对任何人都有用。 I have associated a generic with the element type of the reference我已将泛型与引用的元素类型相关联

```const containerRef = useRef<View>(null); ```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM