让一个简单的滚动动画在 react-native 中工作

Getting a simple scrolling animation to work in react-native

我正忙于尝试让一个简单的滚动动画在 React Native 中工作。

我想要实现的是组件在被点击后滚出屏幕的右边缘。

无论我用这个 class 做什么,当我点击该元素时我都会收到错误 Attempted to assign to readonly property,我不明白为什么。

我能看到在 animateOut 函数中发生的唯一赋值是 this.anim.offsetX,但这不能是只读的 属性,因为我清楚地赋值给它就好了构造函数。

我尝试过但没有帮助的事情:

  1. 从状态 属性 中取出可动画值,因此 animated.timing 调用不会尝试直接改变状态 属性.

  2. 简化动画调用,这样只有一个动画会改变这个值。

  3. 仔细阅读示例:the reactjs animation docs 看看我在做什么。

  4. 查找有关堆栈溢出的现有问题。我找到了 ,但那里的错误条件似乎不适用于我的代码。

有人可以告诉我我做错了什么吗?

    export default class SquareBlock extends Component {

    constructor(props) {
        super(props);
        this.anim = {};
        this.anim.offsetX = new Animated.Value(0);

    }

    animateOut() {
        console.log("animating out");

        console.log("X offset:",this.anim.offsetX)

        Animated.timing(
           this.anim.offsetX,
           { toValue: 120,
             duration: 500
           }
        ).start();


    }


    render() {

        let content = this.props.content || "Tappable";
        let offsetX;

        offsetX = this.anim.offsetX;

        return (
            <Animated.View >
            <TouchableNativeFeedback onPress={ () => this.animateOut() }>
                <View style={ [styles.outerBox, { "left": offsetX } ]  }  >

                    <Text style={ styles.text }> { content }</Text>

                </View>
            </TouchableNativeFeedback>
            </Animated.View>
        )

    }

}

你必须设置X和Y的值,然后给Animated.View

另外,你还得给动画提供样式(至少样式是动画使用的道具名称)。

试试这个:

在componentWillMount()中有一个你想开始的位置

componentWillMount() {
        //important
        this.position = new Animated.ValueXY({x: 30 , y: 0});
}

在你的 Animated.View 中,你必须提供 this.position 作为样式 //如前所述,样式是动画所采用的道具的名称。

<Animated.View style={this.position.getLayout()}> //very important
    <TouchableNativeFeedback onPress={ () => this.animateOut() }>
                <View style={ [styles.outerBox, { "left": offsetX } ]  }  >

                    <Text style={ styles.text }> { content }</Text>

                </View>
    </TouchableNativeFeedback>
 </Animated.View>

animateOut() {    
         this.position ,
         Animated.timing(this.position, {
            toValue: { x: this.position + 20 , y: 0},
            duration: 250
         }).start();
}

这应该可以正常工作