[英]How can I render a component in DOM body even if some other component renders it in react?
I have a component, say X
which is rendered by my app
and in the DOM-body. 我有一个组件,比如X
,它由我的app
和DOM体中呈现。 I have another component Y
which is rendered by the component X
but the component Y
should be opened in full-screen. 我有另一个组件Y
,它由组件X
渲染,但组件Y
应该全屏打开。 So, I need to render this in document.body
rather inside component X
even if X
renders it. 所以,我需要在document.body
渲染它,而不是在组件X
即使X
渲染它。
React Components' structure is: React Components的结构是:
app
-X
-Y (in Full Screen)
the structure now should look like: 结构现在应该是这样的:
<body>
<div class="X">
<div class="Y">
</div>
</div>
</body>
and the rendered flow should be : 并且渲染的流程应该是:
app.body
-X
-Y
and the DOM structure should be: 并且DOM结构应该是:
<body>
<div class="X">
</div>
<div class="Y">
</div>
</body>
How can I do this. 我怎样才能做到这一点。 Also, I am using ES6 classes for making react-components. 另外,我使用ES6类来制作反应组件。
UPDATE: Starting from React 16 , there is official support for portals . 更新:从React 16开始,官方支持门户网站 。
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. 门户网站提供了一种将子项呈现为存在于父组件的DOM层次结构之外的DOM节点的第一类方法。
I wouldn't recommend to use this solution as it is using an undocumented React API . 我不建议使用此解决方案,因为它使用的是未记录的React API 。 Disclaimer provided, here it is: 免责声明,这里是:
class Portal extends React.Component { componentDidUpdate() { this._renderLayer(); } componentDidMount() { this._renderLayer(); } componentWillUnmount() { ReactDOM.unmountComponentAtNode(document.getElementById(this.props.container)); } _renderLayer() { ReactDOM.unstable_renderSubtreeIntoContainer(this, this.props.children, document.getElementById(this.props.container)); } render() { return null; } } class Y extends React.Component { render() { return <div>Y</div>; } } class X extends React.Component { render() { return ( <div> X <Portal container="Y"> <Y /> </Portal> </div> ); } } ReactDOM.render(<X/>, document.getElementById('X'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='X'></div> <div id='Y'></div>
Simply render each of your component in their own <div>
: 只需在自己的<div>
渲染每个组件:
<body>
<div id="app"></div>
<div id="Y"></div>
</body>
And render each component separately: 并分别渲染每个组件:
React.render(ComponentApp, document.getElementById("app"));
React.render(ComponentX, document.getElementById("X"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.