javascript - React native-feil på ref scrollview, men fungerer
Jeg trenger å bla til bunnen av flatlist, så jeg bruker:
const scrollViewRef = useRef();
//my scroll view
<ScrollView
ref={scrollViewRef}
onContentSizeChange={() => {
scrollViewRef.current.scrollToEnd({ animated: true });
}}
men jeg fikk disse feilene:
Den første er:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<ScrollViewProps>): ScrollView', gave the following error.
Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.
Types of property 'current' are incompatible.
Type 'undefined' is not assignable to type 'ScrollView | null'.
Overload 2 of 2, '(props: ScrollViewProps, context?: any): ScrollView', gave the following error.
Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.ts(2769)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'
den andre er:
Object is possibly 'undefined'.
Noen forslag?
Svar #1
Du må sende type til useRef, og scrollViewRef current kan være null, så lag bare en if eller bruk ?-operatoren.
const scrollViewRef = useRef<ScrollView|null>(null);
//my scroll view
<ScrollView
ref={scrollViewRef}
onContentSizeChange={() => {
scrollViewRef?.current?.scrollToEnd({ animated: true });
}}
