9

我的问题是关于在 react 和/或 react-native 动画中使用 translateX 和 translateY 来将对象设置为动画到某个点。

这两个变换相对于现有点移动对象。

但是对于这个场景,现有坐标并不重要,我想确保对象移动到屏幕中可能存在的某个点。

额外的限制是,我不能为样式设置动画top,并且因为在 react-native 中,如果我们为这些样式设置动画bottom,那么我们就不能使用导致性能问题的指令。leftrightuseNativeDriver={true}

4

1 回答 1

10

您可以使用该道具来获取任何组件的onLayout位置(相对于父级)和高度/宽度。View

像这样的东西应该工作。您可能需要获取更多父View组件的位置,具体取决于您当前的结构。

componentDidMount() {
  this.animatedValue = new Animated.Value(0);  
}

animate() {
  const { parentYPosition } = this.state;
  Animated.Timing(this.animatedValue, {
    toValue: FINAL_POSITION - parentYPosition
  }).start(); 
}

render() {
  return (
    <View 
      onLayout={event => {
        const { y } = event.nativeEvent.layout;
        this.setState({parentYPosition: y})
      }}
    >
      <Animated.View 
        style={{
          position: 'absolute',
          top: 0, 
          transform: [
          {
            translateY: this.animatedValue
          }
      />
    />
  );
}

https://facebook.github.io/react-native/docs/view#onlayout

于 2019-05-27T13:19:31.377 回答