React Native 的 Animated.ScrollView 不允许我以编程方式滚动到某个位置

React Native's Animated.ScrollView is not allowing me to programmatically scroll to a certain position

在升级到最新版本的 React-Native 和 Expo 之前,此代码块可以正常工作。它正在处理的版本是 "expo": "^32.0.0"

我以前能够以编程方式移动 Animated.ScrollView 的子级,但现在我不能再这样做了。这是我正在测试的测试代码块。

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Animated,
  TouchableOpacity,
  SafeAreaView,
  ScrollView
} from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }
  handleMove = () => {
    this.scroller.getNode().scrollTo({
      x: 200,
      y: 0,
      animated: false
    });
  };
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Animated.ScrollView
          horizontal
          ref={scroller => {
            this.scroller = scroller;
          }}
        >
          <View
            style={{
              height: 100,
              width: 100,
              backgroundColor: 'red',
              margin: 5
            }}
          />
        </Animated.ScrollView>
        <TouchableOpacity onPress={this.handleMove}>
          <Text>Move</Text>
        </TouchableOpacity>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {}
});

升级后代码块不再适用于最新版本。我正在测试的当前版本是:

"dependencies": {
    "expo": "^34.0.1",
    "react": "16.8.3",
    "react-dom": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
    "react-native-web": "^0.11.4"
  },

正确的做法是什么?

我加了点心来帮助说明我的问题。 ' https://snack.expo.io/@louis345/brave-banana

你可以试试这个

<Animated.ScrollView // <-- Use the Animated ScrollView wrapper
  scrollEventThrottle={1} // <-- Use 1 here to make sure no events are ever missed
  onScroll={Animated.event(
    [
      {
        nativeEvent: {
          contentOffset: {x: 200,y: 0},
        },
      },
    ],
    {useNativeDriver: true}, // <-- Add this
  )}>
  {content}
</Animated.ScrollView>

我从 0.57 升级到 0.60 后遇到了类似的问题。

安装东西的时间似乎发生了变化(在 RN 版本之间)。我将再次检查我的代码(几天后),因为我怀疑我正在使用一些即将弃用的生命周期函数。他们现在被认为 "unsafe" 使用的事实可能是由于一些时间问题(随意猜测)。

我通过简单地将 scrollTo 设置为 100 毫秒超时来使我的代码工作。这表明滚动视图在第一次尝试时没有完全安装。我实际上对我的用例超时没问题,但我还是想解决这个问题,因为我不喜欢 hacky 解决方案。

我能够通过向 scrollView 添加一个道具来解决我的问题。 scrollToOverflowEnabled={true}

现在一切正常。我希望这对将来的人有帮助。

我能够通过使用 1 秒的简单 setTimeout 来实现它。

这是我的代码现在的样子:

setTimeout(() => {
  this.scrollView.scrollTo({
    x: DEVICE_WIDTH * current_index,
    y: 0,
    animated: false
  });
}, 1)

与 Micheal 上面的建议类似,这可能是由于 React 中已弃用的 componentWillMount 未在 ScrollView 中正确更新而导致的安装问题引起的。