【问题标题】:How to integrate/use OrgChart plugin with React JS如何将 OrgChart 插件与 React JS 集成/使用
【发布时间】:2019-04-15 03:56:22
【问题描述】:

我正在寻找一个 react 插件来显示基于我在我的 React 应用程序中传递给它的 JSON 数据的组织结构图。我需要基本功能,例如如果用户单击组织结构图中的员工,然后我会返回该员工的完整个人资料信息作为回报。我已经搜索过它并想出了“OrgChart”插件,但现在我不明白如何将这个插件与 react.js 一起使用,因为我是 react.js 的初学者,所以不知道如何集成。所以它如果你能给我提供代码会很有帮助。

我已经看到 this 链接,但由于知识较少,我无法理解将以下代码与正确的文件层次结构放在 react.js 中的何处。

class OrgChart extends React.Component {
  componentDidMount() {
    this.$el = $(this.el);
    let datascource = {
      'name': 'Lao Lao',
      'title': 'general manager',
      'children': [
        { 'name': 'Bo Miao', 'title': 'department manager' },
        { 'name': 'Su Miao', 'title': 'department manager',
          'children': [
            { 'name': 'Tie Hua', 'title': 'senior engineer' },
            { 'name': 'Hei Hei', 'title': 'senior engineer',
              'children': [
                { 'name': 'Pang Pang', 'title': 'engineer' },
                { 'name': 'Xiang Xiang', 'title': 'UE engineer' }
              ]
            }
          ]
        },
        { 'name': 'Hong Miao', 'title': 'department manager' },
        { 'name': 'Chun Miao', 'title': 'department manager' }
      ]
    };

    this.$el.orgchart({
      'data' : datascource,
      'nodeContent': 'title',
      'pan': true,
      'zoom': true
    });
  }

  componentWillUnmount() {
    this.$el.empty();
  }

  render() {
    return (
      <div id="chart-container" ref={el => this.el = el}></div>
    );
  }
}

function Example() {
  return (
    <div>
      <OrgChart></OrgChart>
    </div>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('root')
);

【问题讨论】:

    标签: reactjs orgchart


    【解决方案1】:

    我也试过这个 Codepen 例子。

    首先,您需要安装 jqueryorgchart(我为此使用了 npm)。 对于 TypeScript,还需要安装 @types/jquery

    然后你需要将它们导入到你的 React 组件中。

    import $ from "jquery";
    const orgchart = require("orgchart");
    

    (为了允许这个导入,我还在 tsconfig.json 的 compilerOptions 中添加了 "allowSyntheticDefaultImports": true。)

    您还需要在组件中声明您的 $elel 字段:

    public $el;
    public el;
    

    现在已经准备好了,你可以将给定的 componentDidMount 和 componentWillUnmount 添加到你的组件并返回

    <div id="chart-container" ref={el => this.el = el}></div>
    

    来自您的渲染方法。

    【讨论】:

    • 因为我不使用打字稿,所以我不需要这两个公开声明。代码按预期运行。顺便说一句,Codepen 示例让我不仅为这个 orgchart 插件找到解决方案,还为其他 jquery 插件找到解决方案。我立刻想起了 React 文档中讨论与其他库(尤其是 jquery)集成的部分。
    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 2019-12-25
    • 2019-05-14
    • 2017-12-28
    • 1970-01-01
    • 2021-03-15
    • 2014-02-13
    • 1970-01-01
    相关资源
    最近更新 更多