我正在尝试构建一个组件,该组件:
- 接受子元素并
- 在DOM中呈现子元素,并且还要
- 为文档记录将子元素DOM显示在
pre
中
一种解决方案是将JSX作为单独的prop
传递。这使得它重复了,因为我已经能够通过this.props.children
访问它。理想情况下,我只需要以某种方式将children
prop转换为string
,以便我可以在pre
中呈现它,以显示"此代码产生此结果"。
到目前为止,这就是我的进展
class DocumentationSection extends React.Component{
render(){
return <div className="section">
<h1 className="section__title">{heading || ""}</h1>
<div className="section__body"> {this.props.children}</div>
<pre className="section__src">
//Change this to produce a JSX string from the elements
{this.props.children}
</pre>
</div>;
}
}
当我渲染DocumentationSection时,如何获得格式为'<Div className='myDiv'>...</Div>
的jsx字符串?
<DocumentationSection heading='Heading 1'>
<Div className='myDiv'>...</Div>
</DocumentationSection>
谢谢。
编辑:
我尝试了toString,但它没有起作用,显示 [object Object]。