scrollTo 在动画 ScrollView 上未定义



使用 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

它在普通的滚动视图上工作正常。有什么办法可以解决这个问题吗?

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

由于此拉取请求,获取包装组件ref的新且面向未来的方法是使用 getNode() 实用程序方法,因为访问私有变量(以 _ 开头(对未来的 API 更改并不安全。

所以,新的方法是

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

然后在调用该方法时,执行

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

:-(

尝试这样做来获取组件从Animated.createAnimatedComponent方法返回的 ref:

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

然后,调用this.list.scrollTo({x: 0, y: 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})

编辑:从RN 0.62开始,不再需要以下内容

但是,在使用Animated组件时,我们将进入直接操作,这要求我们在调用任何静态方法之前获取组件的本机节点。因此,您最终会得到以下内容:

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

只是添加另一个答案作为"getNode"和"_component"解决方案对我不起作用。我正在使用反应原生 0.57。设法使其使用滚动到偏移量工作

componentDidMount() {
  this.refs.listRef.scrollToOffset({ offset: 0,  animated: false })
}
render() {
  return (
    <FlatList ref="listRef" ... />
  }
};

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

const ScrollViewX = Animated.createAnimatedComponent(ScrollView);

  _scrollView = React.createRef();
<ScrollViewX
      ref={this._scrollView}>

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

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

(ScrollToOffset 已弃用,可能在 0.6 中被删除(

最新更新