操作DOM问题

来源:8-5 组件的Refs(操作DOM的二种方法)

慕工程1096074

2017-06-08

changeUserInfo(name){ 
        this.setState({username: name});
        var mySubmitButton = document.getElementById('submitButton');
        // ReactDOM.findDOMNode(mySubmitButton).style.color = 'blue';
         mySubmitButton.style.color = 'blue';
    };

操作DOM的时候一定要用ReactDOM.findDOMNode(mySubmitButton)吗?我直接改style也成功了

写回答

1回答

JS菌

2017-06-10

function findDOMNode(componentOrElement) {

  if ("development" !== 'production') {

    var owner = ReactCurrentOwner.current;

    if (owner !== null) {

      "development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : void 0;

      owner._warnedAboutRefsInRender = true;

    }

  }

  if (componentOrElement == null) {

    return null;

  }

  if (componentOrElement.nodeType === 1) {

    return componentOrElement;

  }


  var inst = ReactInstanceMap.get(componentOrElement);

  if (inst) {

    inst = getHostComponentFromComposite(inst);

    return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;

  }


  if (typeof componentOrElement.render === 'function') {

    !false ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0;

  } else {

    !false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0;

  }

}


0
2
JS菌
回复
慕工程1096074
源码够清楚的了
2017-06-12
共2条回复

结合基础与实战学习React.js 独立开发新闻头条平台

轻松入门 React 开发,React Router 4 与 Webpack 2 完美升级项目

2768 学习 · 2126 问题

查看课程