【问题标题】:React Native ScrollView scrollTo function is not workingReact Native ScrollView scrollTo 功能不起作用
【发布时间】:2019-03-23 17:28:19
【问题描述】:

我正在尝试滚动到顶部,如果满足某个条件,在组件的componentWillReceiveProps 事件中......但没有任何反应:

componentWillReceiveProps(nextProps) {
     // some code...

    if (newQuery === query && this.scrollViewRef.current) {
      console.log('Should scroll to top'); // << logs successfully

      this.scrollViewRef.current.scrollTo({
        x: 0,
        y: 0,
        duration: 500,
        animated: true,
      });
    }
  }

我如何为 scrollView 创建 ref 的代码 sn-p:

class SearchResult extends React.Component {
  constructor(props) {
    super(props);

    this.scrollViewRef = React.createRef();
  }
//...
}

渲染方法:

render () {
   return (
      <ScrollView
        ref={this.scrollViewRef}
        contentContainerStyle={{ marginVertical: 8 }}
      >
    ...
    )
}

我还尝试通过按下按钮手动滚动...也不起作用

有什么帮助吗?

【问题讨论】:

  • 有错误提示吗?
  • 什么都没有……我登录了this.scrollViewRef.current,并且有scrollTo函数
  • 你试过this.scrollViewRef.getNode().scrollTo()吗?
  • 不幸的是,它给出了这个错误:this.scrollVieeRef.getNode is not a function ...
  • 啊有趣,很高兴你解决了它。

标签: reactjs react-native


【解决方案1】:

我想通了……

scrollView 在一个孤立的环境(一个全新的项目)中完美运行......

我认为问题可能出在该滚动视图的容器中......我发现父组件也有一个ScrollView......一旦我删除它,一切都运行良好。

【讨论】:

    【解决方案2】:

    对于那些使用useRef()方法并得到'xRef.scrollTo' is not a function错误的人,尝试像xRef.current.scrollTo({[YOUR_PARAMS]})一样使用它。

    我不知道 current 这件事,我快疯了。

    【讨论】:

      【解决方案3】:

      React Native 文档说:

      注意:奇怪的函数签名是由于历史原因,该函数还接受单独的参数作为选项对象的替代。由于不明确(x 之前的 y),这已被弃用,不应使用。

      如果您还使用带有 ScrollView 的 FlatList,不妨试试 scrollToOffset 方法?

      【讨论】:

      • 谢谢,但这是一个警告,不要使用 scrollTo (x, y, animation) 的旧签名...我们应该使用 scollTo({ x: 5, y: 5, animated: true } ) ...这就是我目前使用的....而且我的问题中的代码不会引发任何错误甚至警告
      • 我明白了。你检查过this question 看看这是否相似??
      • 是的,我在发布之前做了自己的研究......我遇到了这个 stackoverflow 帖子......尝试了其中的所有内容......效果不佳......但还是谢谢你
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多