【问题标题】:Why is the type of ref not recognized in the child component?为什么子组件中不识别 ref 的类型?
【发布时间】:2021-12-16 02:47:35
【问题描述】:

我在 ScrollView 中传递了一个组件,并且在那里我也传递了 ref。

const GameMulti: FC<GameMultiProps> = ({ navigation }) => {
  const scrollViewRef = useRef<ScrollView & scrollViewProps>(null);
// Should be:
// const scrollViewRef = useRef<ScrollView & React.RefObject<ScrollView>>(null);
...

 <ScrollView
          ref={scrollViewRef}

>

  <DetailedAnswer
    scrollViewRef={scrollViewRef}
  />

...

DetailedAnswer.tsx

export type scrollViewProps = {
  current: {
    scrollTo: ({ y, animated, }: { y: number, animated: boolean }) => { y: number, animated: boolean }
  }
};

interface Props {
  scrollViewRef: ScrollView & scrollViewProps
// Should be:
// scrollViewRef: React.RefObject<ScrollView>
}

const DetailedAnswer: FC<Props> = ({ scrollViewRef }) => {

  if (scrollViewRef.current) // not needed
    scrollViewRef.current?.scrollTo({ y: 0, animated: true });

我创建了scrollViewProps,因为来自react-nativecurrent 给了我一个错误。

但现在我在上面得到一个错误:

 <DetailedAnswer
    scrollViewRef={scrollViewRef}
  />


Type 'RefObject<ScrollView & scrollViewProps>' is not assignable to type 'ScrollView & scrollViewProps'.
  Type 'RefObject<ScrollView & scrollViewProps>' is missing the following properties from type 'ScrollView': scrollTo, scrollToEnd, flashScrollIndicators, getScrollResponder, and 38 more.ts(2322)
DetailedAnswer.tsx(33, 3): The expected type comes from property 'scrollViewRef' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

【问题讨论】:

  • 快速回答 - 这个scrollViewRef 不返回与scrollViewProps 相同的类型 - scrollViewProps 不是 RefObject,因此它缺少很多属性。这有帮助吗?还有其他问题吗?

标签: reactjs typescript react-native scrollview use-ref


【解决方案1】:

正如@jnelson 所说(有点),scrollViewRef 的类型应该是 RefObject。

interface Props {
  scrollViewRef: React.RefObject<ScrollView>;
}

您不需要创建单独的类型作为 scrollViewProps。

另外,仅供参考,如果您要使用可选链接,则无需检查 scrollViewRef.current 是否真实。您可以删除if (scrollViewRef.current)scrollViewRef.current?.scrollTo 就足够了。

【讨论】:

  • 嗨@Ugur,感谢您的解决方案。现在一切正常。
  • @FotiosTsakiris 很高兴,但您编辑了您的帖子并包含了const scrollViewRef = useRef&lt;ScrollView &amp; React.RefObject&lt;ScrollView&gt;&gt;(null);。 useRef 添加了 RefObject 类型,你不需要传递它。事实上,这会破坏你的代码。应该是const scrollViewRef = useRef&lt;ScrollView&gt;(null);。我们使用 RefObject 是因为 useRef 挂钩返回 RefObject&lt;T&gt;,而不是我们传递的类型。因此,通过您的编辑,返回类型现在是 RefObject&lt;RefObject&lt;ScrollView&gt;&gt; 而不是 RefObject&lt;ScrollView&gt;。这不是您想要的类型。
  • 对!但是,没有 ScrollView,我得到了 2 个错误。一个来自 ScrollView 中的 ref:Type 'RefObject&lt;RefObject&lt;ScrollView&gt;&gt;' is not assignable to type 'string | RefObject&lt;ScrollView&gt; | ((instance: ScrollView | null) =&gt; void) | null | undefined'. 另一个用于我传递 ref 的子组件:Type 'RefObject&lt;RefObject&lt;ScrollView&gt;&gt;' is not assignable to type 'RefObject&lt;ScrollView&gt;'.
猜你喜欢
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
  • 2013-06-12
  • 2012-02-12
相关资源
最近更新 更多