jQuery UI可以使用React.js buggy进行排序

时间:2015-04-19 02:30:14

标签: jquery-ui reactjs jquery-ui-sortable reactjs-flux

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

目前,当你拖放一个项目时,jQuery UI DnD可以工作,但是UI中项目的位置不会改变,即使页面使用更新的数组重新渲染。即,在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>
          )
      }
  });

3 个答案:

答案 0 :(得分:9)

诀窍是在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)))))
        }
    })
}

答案 1 :(得分:6)

jQuery UI Sortable与React不兼容的原因是因为它直接改变了DOM,这在React中是一个很大的 no no

要使其正常工作,您必须修改jQuery UI Sortable以便保留DnD功能,但是当您删除元素时,不会修改DOM 。相反,它可以触发一个事件,该事件触发具有元素的新位置的React渲染。

答案 2 :(得分: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(你需要知道的一切都在这里)

希望这有意义并解决您的问题