React native bind animated event
Asked Answered
M

2

6

Need a little help with some JS. Is it possible to bind an animated event as needed below?

I need to do this:

onScroll={
    Animated.event([
        {
            nativeEvent: {
                contentOffset: {y: this.state.animTop}
            }
        }
    ])
}    

I also need to do this

onScroll={(e) => {
    let positionY =  e.nativeEvent.contentOffset.y;
    this._handleScroll(positionY);
    this.setState({y: positionY})

}}

I have tried binding both like this, but it not take doing the Animated.event

componentDidMount() {
    this._handleScroll = this._handleScroll.bind(this);
}
onScroll={
    this._handleScroll
}
_handleScroll(e) {
    Animated.event([
        {
            nativeEvent: {
                contentOffset: {y: this.state.animTop}
            }
        }
    ]);
    if(e > 30) {
        this.setState({statusBarHidden: true});
    } else {
        this.setState({statusBarHidden: false});
    }
}
Manamanacle answered 10/3, 2017 at 10:52 Comment(0)
M
11

Finally got it work:

Bound the function to the Animated.event listener:

onScroll={Animated.event(
                    [{ nativeEvent: { contentOffset: { y: this.state.animTop } } }],
                    { listener: this._handleScroll },
                )}
Manamanacle answered 10/3, 2017 at 11:18 Comment(0)
N
2

You could also use setValue().

So that would work like this:

_handleScroll(event) {
    // Do stuff
    this.state.animTop.setValue(event.nativeEvent.contentOffset.y);
    // Do other stuff
}
Nasion answered 2/12, 2017 at 15:29 Comment(1)
Please note that Animated.event has the capability to useNativeDriver, whereas .setValue uses the JS thread for animations.Dithionite

© 2022 - 2024 — McMap. All rights reserved.