我在 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}
/>
...
詳細答案.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因為 fromreact-native給了我一個錯誤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; }'
uj5u.com熱心網友回復:
正如@jnelson 所說(有點),型別scrollViewRef應該是一個 RefObject。
interface Props {
scrollViewRef: React.RefObject<ScrollView>;
}
您不需要創建單獨的型別作為 scrollViewProps。
另外,僅供參考,如果您要使用可選鏈接,則無需檢查 scrollViewRef.current 是否為真。您可以洗掉if (scrollViewRef.current). scrollViewRef.current?.scrollTo就足夠了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343871.html
