动画 API 的 createAnimatedComponent 使 FlatList 的 ref 在 react-native 中未定义

bat*_*top 1 react-native react-native-scrollview react-animated react-native-flatlist

我想要使用scrollToIndex的功能FlatList上作出反应,本地人。但是,当我切换FlatList到 时createAnimatedComponent(FlatList),它ref变成了undefined

有没有办法在我使用时保持FlatList's ?refcreateAnimatedComponent

谢谢你的关心。

Mik*_*tin 8

当前createAnimatedComponent公开了一个被调用的方法getNode(),该方法应该用于获取对底层组件的引用。这里有两个例子,一个是旧的,一个是新的

// old ref style
class DemoComp extends Component {
  componentDidMount() {
    // setTimeout is needed for scrollToOffset ¯\_(?)_/¯
    setTimeout(() => {
      this.listRef.getNode().scrollToOffset({ offset: 100, animated: true });
    }, 0);
  }

  render() {
    return <Animated.FlatList ref={r => { this.listRef = r; }} {...otherProps} />;
  }
}

// new ref style
class DemoComp extends Component {
  listRef = React.createRef();

  componentDidMount() {
    // setTimeout is needed for scrollToOffset ¯\_(?)_/¯
    setTimeout(() => {
      this.listRef.current.getNode().scrollToOffset({ offset: 100, animated: true });
    }, 0);
  }

  render() {
    return <Animated.FlatList ref={this.listRef} {...otherProps} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

最终,将来createAnimatedComponent将切换到“转发引用”,它仅适用于新样式。但由于所有依赖旧样式的库,这一天还有很长的路要走。

附注。如果您在遥远的将来阅读本文,您可以在createAnimatedComponent此处查看转发参考的状态:https : //github.com/facebook/react-native/issues/19650