How to handle special Bootstrap events in React?

雨燕双飞 提交于 2021-02-06 02:38:23

问题


In straight up jQuery, I can do something like

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

but is there a "right" way to do it in React? If the above is the way to go, where should I place that event handler? Please note that I am not using the react-bootstrap plugin.


回答1:


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 (
      <div ref={node => (this.myCollapsible = node)} />
    )
  }
}

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




回答2:


I know I'm more than two years late to answer this question but I ran into this same problem recently and Fausto NA's answer didn't work for me. I was able to successfully attach my event listeners by leveraging the affected component's componentDidMount method:

import $ from 'jquery';
import React from 'react';

class App extends React.Component {

    componentDidMount() {
        $('#myCollapsible').on('click', 'hidden.bs.collapse', function () {
            alert('#myCollapsible -- hidden.bs.collapse');
        })
    }

    render() {
        return (
            // This is the render method where `#myCollapsible` would be added to the DOM. 
        )
    }
}

Why this works: if you try attaching an event handler to an element that isn't currently in the DOM then jQuery won't be able to successfully attach an event to it. In the example above, the jQuery code within the componentDidMount method doesn't run until #myCollapsible is in the DOM. This ensures jQuery can find it and properly attach your event handler.



来源:https://stackoverflow.com/questions/36698746/how-to-handle-special-bootstrap-events-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!