为什么在子组件中无法识别 ref 的类型?

Why is the type of ref not recognized in the child component?

我在 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 给我一个错误 current

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

 <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; }'

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

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

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

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