最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add event listener in React? - Stack Overflow

programmeradmin4浏览0评论

I'm creating a chat app with a user and agent. I'm trying to retrieve the messages when the agent replies on his separate Rainbow UI. The problem is that this can only be done via an event listener as shown in the documentation. Can someone help me, where and how can I document.addEventListener in React?

Note: getMessageFromConversation() api doesn't work because by default, once the full messsage history has been seen, calling this api will return an error. I've tried it.

Thanks in advance!

I'm creating a chat app with a user and agent. I'm trying to retrieve the messages when the agent replies on his separate Rainbow UI. The problem is that this can only be done via an event listener as shown in the documentation. Can someone help me, where and how can I document.addEventListener in React?

Note: getMessageFromConversation() api doesn't work because by default, once the full messsage history has been seen, calling this api will return an error. I've tried it.

Thanks in advance!

Share Improve this question edited Apr 7, 2020 at 17:48 Han asked Apr 7, 2020 at 16:40 HanHan 4262 gold badges5 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

If you're using class based ponents then you can use ponentDidMount and ponentWillUnmount to add and remove the listener respectively, like this:

class Hello extends React.Component {
  doSomething = () => {}

  ponentDidMount() {
    window.addEventListener('scroll', this.doSomething)
  }

  ponentWillUnmount() {
    window.removeEventListener('scroll', this.doSomething)
  }
}

If you're using hooks then you can use useEffect to add and remove listener like this:

function Hello() {
  useEffect(() => {
    const doSomething = () => {};

    window.addEventListener("scroll", doSomething);
    return () => {
      window.removeEventListener("scroll", doSomething);
    };
  }, []);
}

You can add an eventListener in react doing so in the ponentDidMount so it will be done when the ponent is mounted.

ponentDidMount() {
    document.addEventListener(...)
}
发布评论

评论列表(0)

  1. 暂无评论