简体   繁体   中英

How do I use a custom DOM node to render to from within a react component

I have the following problem:

I want to write jsx code like

<div className="my-section">
   <Window>
       <div>Window content</div>
   </Window>
</div>
<div className="window-container">
</div>

somewhere in my react content, but I want the window to render in a special DOM element with other windows, something like

<div class="my-section"></div>
<div class="window-container">
    <div class="window">
        <div>Window Content</div>
    </div>
</div>

And to do this transparently I need to tell the component to render to a special DOM node from within the component. Is there a way to do this? If not, how should I accomplish the functionality I am looking for from within React ?

You're looking for the special this.props.children list.

When you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags like this:

 <Parent><Child /></Parent> 

Parent can read its children by accessing the special this.props.children prop.

This will allow you to get the children defined inside your element, then insert them at an arbitrary point for render.

render() {
  return (
    <div className="window container">
      <div className="window">{this.props.children}</div>
      <div className="window"></div>
      ...
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM