Javascript 在不同位置内渲染组件

Javascript 在不同位置内渲染组件,javascript,reactjs,Javascript,Reactjs,这是我的react应用程序组件结构 <App> <Body> <Top> ### //<- Position 1 </Top> <Middle> <MyComponent/> </Middle> </Body> </App> 什么时候进口是什么意思 无论如

这是我的react应用程序组件结构

<App>
    <Body>
        <Top>
            ### //<- Position 1
        </Top>
        <Middle>
            <MyComponent/>
        </Middle>
    </Body>
</App>

什么时候进口是什么意思

无论如何,您可以只使用条件渲染。它会做的工作,但似乎你的意图是别的

render(){
 const { showMyComp } = this.state
 return(
   <App>
    <Body>
        <Top>
            {showMyComp && (<MyComponent />)}
        </Top>
        <Middle>
            <MyComponent/>
        </Middle>
    </Body>
   </App>
 )
}
建议在React App范围之外的DOM节点上使用ReactDom.createPortal。在内部,您通常应该声明一个组件

但是出于好奇,如果您只想使用这种方法,那么应该在Top元素中使用DOM节点的ref

您正在获取的目标容器不是DOM元素错误,因为在执行到达ReactDOM.createPortal调用时,document.getElementById'top-render'尝试检索的DOM节点尚未写入DOM

这是因为到那时,React还没有成功地通过组件树。i、 React尚未成功创建组件树中所有内容的虚拟表示,因此,尚未向DOM写入任何内容。因此,尽管您希望DOM中有顶级的render div,但实际上它还没有被编写出来


解决方案是创建一个由拥有的DOM节点。您能提供一个您尝试过的代码示例吗?我会稍后再做。@HenryWoody我编辑过。如何导出refif有一个id top呈现,您只需使用document.getElementByIdtop-render获取元素您能格式化代码以使用我的组件命名策略吗,“名字不同,对我来说有点难理解。”布布尼奥当然可以。
render(){
 const { showMyComp } = this.state
 return(
   <App>
    <Body>
        <Top>
            {showMyComp && (<MyComponent />)}
        </Top>
        <Middle>
            <MyComponent/>
        </Middle>
    </Body>
   </App>
 )
}
ReactDOM.createPortal(
    <MyComponent/>,
    /*Ref of Container element*/,
);
const MyCustomComponent = () => {
  return (<div>Demo Text: from "MyCustomComponent"</div>)
}

class MyComponent extends React.Component {
  el = document.createElement("div");

  componentDidMount() {
    // saving this on the component so we can access it in `componentWillUnmount` later
    this.targetEl = document.getElementById("top-render");
    this.targetEl.appendChild(this.el);
  }

  componentWillUnmount() {
    this.targetEl.removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(<MyCustomComponent />, this.el);
  }
}