admin管理员组

文章数量:1291031

I'm trying to scroll to the end of my FlatList when the state of messages changes. Currently I'm using this.refs.flatList.scrollToEnd(); after waiting a bit, which works OK. What I want to do is add an event listener to the messages state so that when the list is changed in any way it will scroll to the end of the list. I tried

ponentDidMount(){
        this.state.messages.addEventListener('change', this._handleNewMessage);
}

but it doesn't work. Does anyone know a way I can achieve this?

I'm trying to scroll to the end of my FlatList when the state of messages changes. Currently I'm using this.refs.flatList.scrollToEnd(); after waiting a bit, which works OK. What I want to do is add an event listener to the messages state so that when the list is changed in any way it will scroll to the end of the list. I tried

ponentDidMount(){
        this.state.messages.addEventListener('change', this._handleNewMessage);
}

but it doesn't work. Does anyone know a way I can achieve this?

Share Improve this question edited Oct 22, 2018 at 17:09 Sateesh Yemireddi 4,4091 gold badge22 silver badges39 bronze badges asked Oct 22, 2018 at 14:25 jacob blankenshipjacob blankenship 1711 gold badge4 silver badges19 bronze badges 1
  • "when the list is changed in any way" what do you mean by any way? – Sagiv b.g Commented Oct 22, 2018 at 14:27
Add a ment  | 

1 Answer 1

Reset to default 7

This would be what the lifecycle method ponentDidUpdate is for:

ponentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the ponent has been updated. ...

Naturally, you have to ensure that this.state.messages is only changed via setState—but that was already true, using ponentDidUpdate doesn't change that.

ponentDidUpdate() {
    this.refs.flatList.scrollToEnd();
}

本文标签: javascripthow to add an event listener to a state in react nativeStack Overflow