jQuery UI可排序与React.js越野车

问题描述 投票:6回答:4

我在React中有一个可排序的列表,该列表由jQuery UI提供支持。当我将一个项目拖放到列表中时,我想更新数组,以便将列表的新顺序存储在那里。然后使用更新后的数组重新呈现页面。即this.setState({data: _todoList});

[当前,当您拖放一个项目时,jQuery UI DnD可以工作,但是即使页面使用更新后的数组重新渲染,该项目在UI中的位置也不会改变。即,在用户界面中,即使定义其放置位置的数组已成功更新,该项目仍会恢复到其在列表中的位置。

如果将项目拖放两次,则它将移动到正确的位置。

    // Enable jQuery UI Sortable functionality
    $(function() {
      $('.bank-entries').sortable({
        axis: "y",
        containment: "parent",
        tolerance: "pointer",
        revert: 150,
        start: function (event, ui) {
            ui.item.indexAtStart = ui.item.index();
        },
        stop: function (event, ui) {
            var data = {
                indexStart: ui.item.indexAtStart,
                indexStop: ui.item.index(),
                accountType: "bank"
            };
            AppActions.sortIndexes(data);
        },
      });
    });

    // This is the array that holds the positions of the list items
    var _todoItems = {bank: []};

    var AppStore = assign({}, EventEmitter.prototype, {
      getTodoItems: function() {
        return _todoItems;
      },
      emitChange: function(change) {
        this.emit(change);
      },
      addChangeListener: function(callback) {
        this.on(AppConstants.CHANGE_EVENT, callback);
      },
      sortTodo: function(todo) {
        // Dynamically choose which Account to target
        targetClass = '.' + todo.accountType + '-entries';

        // Define the account type
        var accountType = todo.accountType;

        // Loop through the list in the UI and update the arrayIndexes
        // of items that have been dragged and dropped to a new location
        // newIndex is 0-based, but arrayIndex isn't, hence the crazy math
        $(targetClass).children('form').each(function(newIndex) {
          var arrayIndex = Number($(this).attr('data-array-index'));
          if (newIndex + 1 !== arrayIndex) {
            // Update the arrayIndex of the element
            _todoItems[accountType][arrayIndex-1].accountData.arrayIndex = newIndex + 1;
          }
        });

        // Sort the array so that updated array items move to their correct positions
        _todoItems[accountType].sort(function(a, b){
          if (a.accountData.arrayIndex > b.accountData.arrayIndex) {
            return 1;
          }
          if (a.accountData.arrayIndex < b.accountData.arrayIndex) {
            return -1;
          }
          // a must be equal to b
          return 0;
        });

        // Fire an event that re-renders the UI with the new array
        AppStore.emitChange(AppConstants.CHANGE_EVENT);
      },
    }


  function getAccounts() {
    return { data: AppStore.getTodoItems() }
  }

  var Account = React.createClass({
      getInitialState: function(){
          return getAccounts();
      },
      componentWillMount: function(){
          AppStore.addChangeListener(this._onChange);

          // Fires action that triggers the initial load
          AppActions.loadComponentData();
      },
      _onChange: function() {
          console.log('change event fired');
          this.setState(getAccounts());
      },
      render: function(){
          return (
              <div className="component-wrapper">
                  <Bank data={this.state.data} />
              </div>
          )
      }
  });
jquery-ui reactjs jquery-ui-sortable reactjs-flux
4个回答
10
投票

技巧是在Sortable的sortable('cancel')事件中调用stop,然后让React更新DOM。

componentDidMount() {
    this.domItems = jQuery(React.findDOMNode(this.refs["items"]))
    this.domItems.sortable({
        stop: (event, ui) => {
            // get the array of new index (http://api.jqueryui.com/sortable/#method-toArray)
            const reorderedIndexes = this.domItems.sortable('toArray', {attribute: 'data-sortable'}) 
            // cancel the sort so the DOM is untouched
            this.domItems.sortable('cancel')
            // Update the store and let React update (here, using Flux)
            Actions.updateItems(Immutable.List(reorderedIndexes.map( idx => this.state.items.get(Number(idx)))))
        }
    })
}

6
投票

jQuery UI Sortable无法与React配合使用的原因是,因为它直接使DOM发生突变,而DOM在React中是很大的[[no no。

要使其正常工作,您必须修改jQuery UI Sortable,以便保留DnD功能,但是在删除元素时,它

不修改DOM。相反,它可能会触发一个事件,该事件以元素的新位置触发React渲染。


2
投票
由于React使用虚拟DOM,因此您必须使用React.findDOMNode()函数来访问实际的DOM元素。

我会在组件的componentDidMount方法内调用jQuery UI函数,因为必须已经渲染了元素才能访问。

// You have to add a ref attribute to the element with the '.bank-entries' class $( React.findDOMNode( this.refs.bank_entries_ref ) ).sortable( /.../ );

Documentation - Working with the browser(您需要了解的一切都在这里)

希望并解决您的问题的方法


0
投票
我遇到了同样的问题,可排序小部件的update事件很容易处理。就我而言,我需要一个包含逗号分隔的已排序ID列表的字符串。为此,我在每个项目中都渲染了一个隐藏的输入元素:

$("#container_target").sortable({ items: ".item_target", update: function (e, ui) { var movingId = ui.item.find("input[type=hidden]").val(); var newIndex = ui.item.index(); // Build entire string list here: var ids = ""; $("#container_target input[type=hidden]").each(function(index) { // Add comma if needed if (ids.length) ids += ","; if(index == newIndex) ids += movingId; else if($(this).val() != movingId) ids += $(this).val(); }); } });

© www.soinside.com 2019 - 2024. All rights reserved.