React - getting a component from a DOM element for debugging

前端 未结 10 1041
广开言路
广开言路 2020-11-28 19:02

For the purposes of debugging in the console, is there any mechanism available in React to use a DOM element instance to get the backing React component?

This questi

10条回答
  •  温柔的废话
    2020-11-28 19:43

    v15 and v16 compatible with svg, html, comment, text nodes

    /* Node extends text, svg, html
     usage for node $0:
        $0.reactive // returns [node, parentNode, rootNode]
        $0.react.props // {any:'prop'}
        $0.react.setState(...) // update
     */
    Object.defineProperties(Node.prototype, {
        _react: {writable:true, value:''}
        ,reactKey: {
            get: function(){
                let symbol = this._react;
                if(symbol){ return symbol; }
                // v15, v16 use a string as key, probably a real symbol in the future
                symbol = Object.keys(this).find(key => key.startsWith('__reactInternalInstance$'));
                return Node.prototype._react = symbol || '';
            }
        }
        // try to find the props/state/React-instance
        ,react: {
            get: function(){
                let react = this[ this.reactKey ] || null;
                let $0;
                if(react){
                    $0 = react._currentElement;
                    if($0){ // v15
                        if($0._owner){
                            return $0._owner._instance;
                        }else{
                            return $0;
                        };
                    }
                    $0 = react.return;
                    if($0){ // v16
                        // develop mode only: return react._debugOwner.stateNode
                        // both develop and prod modes:
                        return $0.stateNode
                    }
                }else if(this._reactRootContainer){
                    // v16 _internalRoot === _internalRoot.current.stateNode
                    return this._reactRootContainer._internalRoot;
                }
                return react;
            }
        }
        // make a list of self, ancestors that make up this branch of the tree
        ,reactive: {
            get: function(list=[]){
                let $0 = this;
                while($0 && !$0[ $0.reactKey ] && !$0._reactRootContainer ){
                    $0 = $0.previousSibling;
                };
                if($0 && ($0[$0.reactKey] || $0._reactRootContainer)){
                    list.push($0);
                };
                $0 = this;
                while($0 = $0.parentNode){
                    if($0[ $0.reactKey ] || $0._reactRootContainer){
                        list.push($0);
                    }
                };
                return list;
            }
        }
    });
    

提交回复
热议问题