ReactJS - 在 react 类中初始化 jquery 插件的标准方法是什么

ReactJS - What is the standard method of initializing jquery plugin in a react class?

本文关键字:插件 标准 方法 是什么 jquery 初始化 react ReactJS      更新时间:2023-09-26

我正在使用这个插件 - bootstrap-dropselect

我已经编写了 initDropSelect 函数来初始化这个插件,但我不确定在哪里调用这个函数,因为我想在加载路由后立即将一些 html 附加到 DOM。我正在从两个不同的 ajax 调用中获取数据。必须比较和操作该数据才能将该 html 附加到 DOM("附加到 DOM"注释下面的代码)。

let UserPanel = React.createClass({
  mixins: [LinkedStateMixin],
  getStateFromStores: function() {
    var users = UserStore.getAll();
    // Some more code
    return {
      users: users
      // Other properties
    };
  }
  componentDidMount: function() {
    UserStore.addChangeListener(this._onChange);
  },
  _onChange: function() {
    this.setState(this.getStateFromStores());
  },

  initDropSelect: function() {
    var _self = this;
    var dropSelect = $('#dropselect-demo1').dropselect({
      filter: {
        show: true,
        placeholder: 'Search for an item'
      },
      multiselect: true,
      onselect: function(e, item) {
      },
      onunselect: function(e, item) {
      },
      onclear: function(e) {
      }
    });
    // Append to DOM
    if(this.state.tagsList.length > 0) {
      if(this.state.newLoan.data.tags.length > 0) {
        // Getting data from two different resources
      }
    }
  }
});

请帮助我决定在哪里调用 initDropSelect 来操作来自多个异步请求的数据并将该数据附加到 DOM。

附言我正在使用反应路由器,所以有两种情况。首先,我可能会从其他路线来到这条路线,或者我可以立即重新加载当前页面。

提前谢谢。

一种方法是让渲染方法返回类似<div />的东西,然后您将使用该将 jQuery 组件挂载到其中。挂载后,this将指向您通常会传递给 jQuery 的 DOM 元素。

由于 jQuery 将处理渲染,因此您希望始终从 shouldComponentUpdate() 返回 false。这将防止 React 破坏你的 jQuery 组件。

然后,您可以使用componentDidMount()初始化 jQuery 组件,并在传入新数据时componentWillReceiveProps()更新/重新呈现它。