如何在不进行重大修改的情况下将 vanilla javascript 函数包装到 reactjs

How to wrap vanilla javascript functions to reactjs without major modifications

这是我从 vanilla javascript 到 reactjs

迁移工作的一部分

export const WTree = () => {


    function Tree() {
        this.root = null;
    }


    Tree.prototype.traverse = function(val) {
        this.root.visit(1);
        console.log(this);
        // this.root.visit(this.root);
    }

    Tree.prototype.sorted = function(val) {
        var tree = new Tree();
        this.root.sorted(tree);
        tree.traverse()


    }


    Tree.prototype.addValue = function(val) {

        var n = new Node(val);
        if (this.root == null) {
            this.root = n;   
            // this.root.x = width / 2;
            // this.root.y = 16;
        }
        else {
        this.root.addNode(n);
        }
    }

    Tree.prototype.remove = function(val) {
        // debugger;
        var n = this.search(val)
        if (n != null) {
            if (this.root == n) {

                if (this.root.right != null) {
                    this.root = this.root.right;
                } else if (this.root.left != null) {
                    this.root = this.root.left;
                }

            }
            n.remove();

        }

    }

    Tree.prototype.search = function (val) {
        var found = this.root.search(val);
        if (found == null) {
            console.log(val + ' not found');
        } else {
            console.log(val + ' found');
        }
        return found;
    }



    return Tree
}

我只是将遗留代码包装在

export const WTree = () => { 
}

现在我要在ReactJs中正常使用了

import { WTree } from 'components/binarytree/tree'

class App extends React.Component {

  render() {
    let tree = WTree.Tree
  }
}

但我必须在 100 多个组件上应用类似的逻辑,所以我不想修改或接触太多遗留代码。 现在我失去了 WTree.Tree

的可读性

我正在考虑使用如下简单的方法来提高可读性

class App extends React.Component {

  render() {
    let tree = Tree

  }
}

请帮帮我

看起来您正在尝试做的只是在 React.js 组件内使用数据结构 - 需要 "migration" 或更改任何内容。 React.js 只是一个 UI 库,因此除非您要从一个 UI 库移动到另一个,否则您不必迁移任何东西。

您的 BinaryTree 相关代码不是遗留代码 - 它只是 JavaScript。您不必将任何内容包装在箭头函数中然后将其导出 - 这不是 React 特定的或它需要的东西。

就这样:

function Tree () {
  this.root = null;
}
Tree.prototype.treverse = function(val) { ... }
// ...

export default Tree;

然后在您的 React 组件中,只需执行以下操作:

import Tree from './components/binarytree/tree';

class App extends React.Component {
  constructor(props) {
    this.tree = new Tree()
  }

  componentDidMount() {
    // this is an example of a lifecycle method and how
    // you could use your tree data structure
    this.tree.addValue(...)
  }

  render() {
    // do whatever you need to do here
  }
}

注意:您很可能不想在 render 方法中执行 let tree = new Tree(),因此将其移至 constructor并在其中一种生命周期方法 and/or 事件处理程序中根据需要使用它。


或者,如果您确实想使用 import { Tree } from '...' 语法,您可以通过执行以下操作稍微更改 tree.js

export function Tree () {
  this.root = null;
}
Tree.prototype.treverse = function(val) { ... }
// ...

那么,你可以这样做:

import { Tree } from './components/binarytree/tree';
// ...

希望这对您有所帮助。