scrollTo在动画ScrollView上未定义

时间:2017-02-05 11:13:23

标签: react-native

使用Animated.createAnimatedComponent(ScrollView)创建动画ScrollView时,无法再使用scrollTo

const AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);

<AnimatedScrollView ref={(ref) => this.list = ref}>
  <View style={{height: 1000}} />
</AnimatedScrollView>

调用this.list.scrollTo({x: 0, y: 0})会出现以下错误:

_this.list.scrollTo is not a function

它在普通的ScrollView上运行正常。有什么方法可以解决这个问题吗?

5 个答案:

答案 0 :(得分:31)

@ max23_的回答现在可能有用,但这不是正确的做法 - 根据经验,我们永远不应该直接访问私有变量,因为这些变量经常会发生变化。 (编辑:没有不尊重:-))

由于this pull request,获取包装组件的ref的新的和面向未来的方法是使用getNode()实用程序方法,作为访问私有变量(prepended)使用_)对未来的API更改不安全。

所以,新的做法是

ref={c => (this.myRef = c)}

然后在调用方法时,执行

this.myRef.getNode().scrollTo({
  y: 0,
  animated: true,
});

: - )

答案 1 :(得分:19)

尝试使用Animated.createAnimatedComponent方法获取组件返回的参考:

ref={(ref) => this.list = ref._component}

然后,调用this.list.scrollTo({x: 0, y: 0})应该有效。

答案 2 :(得分:1)

仅添加另一个答案,因为“ getNode”和“ _component”解决方案均不适用于我。我正在使用本机0.57。使用scrollToOffset设法使其工作

componentDidMount() {
  this.refs.listRef.scrollToOffset({ offset: 0,  animated: false })
}

render() {
  return (
    <FlatList ref="listRef" ... />
  }
};

答案 3 :(得分:0)

如果RN> = 0.59(可能更早)和以下参考设置:

const ScrollViewX = Animated.createAnimatedComponent(ScrollView);

  _scrollView = React.createRef();

<ScrollViewX
      ref={this._scrollView}>

您可以通过以下方式手动滚动Animated组件:

this._scrollView.current._component.scrollTo({x: number, y: number, animated: true|false})

(不建议使用ScrollToOffset,并且很可能在0.6版中将其删除)

答案 4 :(得分:0)

以@jhm的答案为基础-自从React 16.3以来,推荐使用一种创建对组件的引用的新方法,就像@cyqui所提到的那样使用React.createRef()

对于普通(注:非动画)组件,我们可以按照推荐的方式简单地创建对ScrollView的引用:

scrollView = React.createRef();

<ScrollView
  ref={this._scrollView}>

以及我们这样的静态方法:

this.scrollView.current.scrollTo({x: number, y: number, animated: true|false})

但是,当使用Animated组件时,我们要进入direct manipulation,这要求我们在调用任何静态方法之前获取组件的本机节点。因此,您将得到以下结果:

scrollView = React.createRef();

<Animated.ScrollView
  ref={this._scrollView}>
this.scrollView.current.getNode().scrollTo({x: number, y: number, animated: true|false})