使用反应排序库对反应元素进行排序

Sorting React elements using a react sorting library

我想使用名为 React Sortable HOC 的 React 排序库。这似乎是一个很棒的库,但我在尝试弄清楚如何在我的实例中使用它时遇到了麻烦。

我将其设置为他们提供的示例之一:

const SortableItem = SortableElement(({ value }) => <li>{value}</li>);

const SortableList = SortableContainer(({ items }) => {
    return (
        <ul>
            {items.map((value, index) => (
                <SortableItem key={`item-${value}`} index={index} value={value} />
            ))}
        </ul>
    );
});

const onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(({ items }) => ({
        items: arrayMove(items, oldIndex, newIndex),
    }));
};

在示例中,他们从这样的状态映射它:

return (
  <SortableContainer onSortEnd={this.onSortEnd}>
    {items.map((value, index) => (
      <SortableItem key={`item-${value}`} index={index} value={value} />
    ))}
  </SortableContainer>
);

但在我的例子中,我使用 'map' 来检查我的状态项(星舰)并生成我的数据,如下所示:

return (
   <div>
      {starships.map((starShip) => (
                <Ship starShip={starShip} />
      ))}
   </div>
);

Ship 这个元素在哪里:

const Ship = ({ ship: { ShipId, ShipName } }) => (
    <tr key={ShipId}>
        <td>{ShipNameName}</td>
    </tr>
);

我不知道如何通过我设置应用程序的方式使用这个库。

有没有人用过这样的?

谢谢!

以下是如何使用它的示例:

const { SortableContainer, SortableElement } = SortableHOC;
const arrayMoveMutate = (array, from, to) => {
  array.splice(
    to < 0 ? array.length + to : to,
    0,
    array.splice(from, 1)[0]
  );
};

const arrayMove = (array, from, to) => {
  array = array.slice();
  arrayMoveMutate(array, from, to);
  return array;
};
function App() {
  const [ships, setShips] = React.useState([
    { ShipName: 'ship a', ShipId: 1 },
    { ShipName: 'ship b', ShipId: 2 },
    { ShipName: 'ship c', ShipId: 3 },
  ]);
  const onSortEnd = React.useCallback(
    ({ oldIndex, newIndex }) => {
      setShips(ships =>
        arrayMove(ships, oldIndex, newIndex)
      );
    },
    []
  );

  return (
    <SortableList items={ships} onSortEnd={onSortEnd} />
  );
}
const SortableList = SortableContainer(({ items }) => {
  return (
    <ul>
      {items.map((ship, index) => (
        <Ship
          key={ship.ShipId}
          index={index}
          value={ship}
        />
      ))}
    </ul>
  );
});

const Ship = SortableElement(
  ({ value }) => <li>{value.ShipName}</li>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-sortable-hoc/0.9.0/react-sortable-hoc.min.js"></script>