Javascript 在React中使用createPortal时,在装载DOM之前触发componentDidMount

Javascript 在React中使用createPortal时,在装载DOM之前触发componentDidMount,javascript,reactjs,Javascript,Reactjs,我的React应用程序中有如下代码: import React from 'react'; import ReactDOM from 'react-dom'; import ComponentB from './ComponentB'; class ComponentA extends React.Component { constructor(props) { super(props); this.condition = this.props.cond

我的React应用程序中有如下代码:

import React from 'react';
import ReactDOM from 'react-dom';
import ComponentB from './ComponentB';

class ComponentA extends React.Component {
    constructor(props) {
        super(props);
        this.condition = this.props.condition;
    }

    render() {
         return ReactDOM.createPortal(
            <div id="abc"></div>,
            document.getElementById('xyz'))
    }

    componentDidMount() {
        ReactDOM.createPortal(
            <div>
                {

                    this.condition &&
                    <ComponentB />
                }
            </div>,
            document.body)
    }
}
基本上,我只想在ComponentA装载到DOM之后呈现ComponentB。因此,我将ComponentA的代码放在ComponentB的componentDidMount中。但ComponentB仍然在ComponentA完成装载到DOM之前呈现


为什么会发生这种情况?这个问题的解决方案是什么?

我不知道您为什么要使用createPortal。但是,如果您只是想实现您的目标,您只需要在第一个组件的componentDidMount中设置您的状态条件,告诉您开始渲染第二个组件

看看这是否有帮助

const ComponentB = () => {

  return (
    <div>Hi is is componentB</div>
  );
}
class ComponentA extends React.Component {
  constructor(props) {
    super (props);

    this.state = {
      renderB: false
    };
  }
  componentDidMount() {
    this.setState({
      renderB: true
    });
  }

  render () {
    let {renderB} = this.state;

    return (
      <div>

        <h3>Hey i am component A</h3>
        {
          renderB? <ComponentB /> : null
        }
      </div>
    );
  }
}

我使用createPortal是因为我需要在ComponentA外部安装ComponentB。因此,你提供的解决办法不足以满足我的目的。