【问题标题】:React Native useRef returns undefined on iOS and Android but works on WebReact Native useRef 在 iOS 和 Android 上返回 undefined 但在 Web 上有效
【发布时间】:2022-06-13 04:57:27
【问题描述】:

我使用 React Native 构建了一个网站,并使用 useRef 滚动到具有 scrollIntoView 的特定元素。

在网上我有这个代码:

import React, { useState, useRef } from 'react';
import { View, ScrollView, Text } from 'react-native';

//Components
import Header from '../components/header';
import MenuBar from '../components/menubar';

export default function Reserveren({ navigation, route }) {

const reserveRef = useRef();

const scrollToElement = (ref) => {
   ref.current.scrollIntoView({ behavior: 'smooth' });
}

return (
   <View>
    <ScrollView>

     <Header navigation={navigation} />
     <MenuBar navigation={navigation} />

    
    <View>
      <Button title="Click me to scroll" onPress={scrollToElement(reserveRef)} />
    </View>

   <View ref={reserveRef}>
     <Text>This is the element to scroll to</Text>
   </View>

  </ScrollView>
</View>
)


}

这段代码在网络上运行得很好,但在 iOS 和 Android 上运行相同的代码会给我一个undefined。我究竟做错了什么?在网上搜索了几个小时,但找不到任何解决方案。

【问题讨论】:

    标签: android ios reactjs react-native ref


    【解决方案1】:

    onPress={scrollToElement(reserveRef)}

    您在渲染组件期间调用scrollToElement 函数,而不是在用户按下按钮时调用它。

    要处理按钮按下,您必须将函数传递给onPress,例如:
    onPress={() =&gt; scrollToElement(reserveRef)}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      相关资源
      最近更新 更多