我有以下问题:
我想编写 jsx
代码,例如
<div className="my-section">
<Window>
<div>Window content</div>
</Window>
</div>
<div className="window-container">
</div>
在我的 react
内容中的某处,但我希望窗口与其他窗口一起呈现在特殊的 DOM
元素中,例如
<div class="my-section"></div>
<div class="window-container">
<div class="window">
<div>Window Content</div>
</div>
</div>
为了透明地执行此操作,我需要告诉组件从组件内渲染到特殊的 DOM
节点。有没有办法做到这一点?如果没有,我应该如何从 React
中实现我正在寻找的功能?
最佳答案
您正在寻找特殊的 this.props.children
列表。
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.
这将允许您在元素内定义子元素,然后将它们插入到任意点进行渲染。
render() {
return (
<div className="window container">
<div className="window">{this.props.children}</div>
<div className="window"></div>
...
</div>
);
}
关于javascript - 如何使用自定义 DOM 节点在 React 组件中进行渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35200985/