How to handle special Bootstrap events in React?

前端 未结 2 941
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 09:35

In straight up jQuery, I can do something like

$(\'#myCollapsible\').on(\'click\', \'hidden.bs.collapse\', function () {
  // do something…
})

2条回答
  •  悲&欢浪女
    2021-02-04 10:10

    The right way to handle events not directly supported by React is by adding an event listener to the DOM node after the component mounts, and removing it when the component unmounts:

    class MyCollapsible extends React.Component {
      constructor() {
        super()
        // Bind the method in the constructor instead of binding it in render, so you only do it once
        this.handleHiddenBsCollapse = this.handleHiddenBsCollapse.bind(this)
      }
    
      componentDidMount() {
        this.myCollapsible.addEventListener('hidden.bs.collapse', this.handleHiddenBsCollapse)
      }
    
      componentWillUnmount() {
        this.myCollapsible.removeEventListener('hidden.bs.collapse', this.handleHiddenBsCollapse)
      }
    
      handleHiddenBsCollapse(event) {
        // Do something...
      }
    
      render() {
        // Settings refs with node => this.bla = node is recommended
        // because this.refs is deprecated.
        // in this example "node" is the DOM node itself, not a react reference
        return (
          
    (this.myCollapsible = node)} /> ) } }

    Documentation for using DOM refs: https://facebook.github.io/react/docs/refs-and-the-dom.html

提交回复
热议问题