我正在使用jsdom在节点中使用React . 当我尝试渲染包含具有内容的另一个组件的组件时,它将无法呈现子组件内容 . 例如,
var React = require('react');
var SubComponent = React.createClass({
render: function() {
return React.createElement("div");
}
});
var TestComponent = React.createClass({
render: function () {
/* JSX would look like this:
<div>
<p>regular tag</p>
<SubComponent>sub component</SubComponent>
</div>
*/
return React.createElement(
"div", {},
React.createElement("p", {}, "regular tag"),
React.createElement(SubComponent, {}, "sub component")
);
}
});
global.document = require('jsdom').jsdom('<!doctype html><html><body></body></html>');
global.window = document.parentWindow;
global.navigator = window.navigator;
React.render(React.createElement(TestComponent),global.document.body)console.log(document.body.innerHTML);
这会将以下标记记录到控制台:
<div data-reactid=".zf2pciql8g">
<p data-reactid=".zf2pciql8g.0">regular tag</p>
<div data-reactid=".zf2pciql8g.1"></div>
</div>
请注意 <p>
标记有其内容,但 <SubComponent>
标记已更改为空div .
为什么div没有“子组件”作为其内在内容?我只是在学习React,所以我在做一些明显愚蠢的事情吗?
1 回答
当您执行
React.createElement(SubComponent, {}, "sub component")
时,您通过this.props.children
将"sub component"
传递给SubComponent
. 但是,在SubComponent
中,您没有使用this.props.children
而只是通过React.createElement("div")
渲染空div .一个简单的解决方法是将
this.props.children
传递给您在SubComponent
的render
方法中创建的div:有关
this.props.children
的更多信息,请参见Type of the Children props .