Реагировать на сортируемое дерево фиксированной глубины при падении - PullRequest
2 голосов
/ 16 апреля 2019

Я использую RST для добавления узлов из внешнего компонента в мое дерево, я пытаюсь сделать так, чтобы при перетаскивании / из внешнего узла он располагался на фиксированной глубине и оставался там, сейчас Я видел захваченные примеры, с которыми я могу работать, но в чем я не уверен, так это в том, как назначить фиксированное падение глубины для каждого внешнего узла, например, уровень 3 не может идти, за исключением уровня 2, и то же самое для всех уровней, которые они должны быть Ниже приведен пример, демонстрирующий мой вопрос.

https://codesandbox.io/embed/k9oq47roj5?fontsize=14

index.js

import { render } from "react-dom";
import "react-sortable-tree/style.css";
/* eslint-disable react/no-multi-comp */
import React, { Component } from "react";
import PropTypes from "prop-types";
import { DragDropContext, DragSource } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
import {
  SortableTreeWithoutDndContext as SortableTree,
  getNodeAtPath
} from "react-sortable-tree";

// -------------------------
// Create an drag source component that can be dragged into the tree
// https://react-dnd.github.io/react-dnd/docs-drag-source.html
// -------------------------
// This type must be assigned to the tree via the `dndType` prop as well
const externalNodeType = "yourNodeType";
const externalNodeSpec = {
  // This needs to return an object with a property `node` in it.
  // Object rest spread is recommended to avoid side effects of
  // referencing the same object in different trees.
  beginDrag: componentProps => ({ node: { ...componentProps.node } })
};
const externalNodeCollect = (connect /* , monitor */) => ({
  connectDragSource: connect.dragSource()
  // Add props via react-dnd APIs to enable more visual
  // customization of your component
  // isDragging: monitor.isDragging(),
  // didDrop: monitor.didDrop(),
});
class externalNodeBaseComponent extends Component {
  render() {
    const { connectDragSource, node } = this.props;

    return connectDragSource(
      <div
        style={{
          display: "inline-block",
          padding: "3px 5px",
          background: "blue",
          color: "white"
        }}
      >
        {node.title}
      </div>,
      { dropEffect: "copy" }
    );
  }
}
externalNodeBaseComponent.propTypes = {
  node: PropTypes.shape({ title: PropTypes.string }).isRequired,
  connectDragSource: PropTypes.func.isRequired
};
const YourExternalNodeComponent = DragSource(
  externalNodeType,
  externalNodeSpec,
  externalNodeCollect
)(externalNodeBaseComponent);

class UnwrappedApp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      treeData: [
        {
          title: "Level 1",
          children: [
            {
              title: "Level 2",
              children: [
                {
                  title: "Level 3",
                  children: [
                    { title: "Level 4", children: [{ title: "Level 5" }] }
                  ]
                }
              ]
            }
          ]
        }
      ]
    };
  }

  render() {
    return (
      <div>
        <div style={{ height: 300 }}>
          <SortableTree
            treeData={this.state.treeData}
            onChange={treeData => this.setState({ treeData })}
            dndType={externalNodeType}
            //   canNodeHaveChildren={node => !node.noChildren}
            canDrop={({ nextParent }) => !nextParent || !nextParent.noChildren}
            addAsFirstChild={!this.state.addAsFirstChild}
          />
        </div>
        <YourExternalNodeComponent node={{ title: "Level 1" }} />
        &nbsp;
        <YourExternalNodeComponent node={{ title: "Level 2" }} />
        &nbsp;
        <YourExternalNodeComponent node={{ title: "Level 3" }} />
        &nbsp;
        <YourExternalNodeComponent node={{ title: "Level 4 or 5" }} />
        &nbsp;
      </div>
    );
  }
}

const App = DragDropContext(HTML5Backend)(UnwrappedApp);
export default App;

render(<App />, document.getElementById("root"));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...