问题
Just wondering if this is possible.
I have a parent component like so:
const React = require('react');
module.exports = React.createClass({
render: function(){
return (
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
{this.props.child}
</body>
</html>
)
}
});
what I would like to do is 'pass' a child component to the parent component using props.
Something like this:
const child = React.createClass({
//// etc
});
ReactDOMServer.renderToString(<HTMLParent child={child}/>);
Normally, a parent component would have "hard-coded" reference to its children. But what I am looking for is a pattern for a parent React component to be able to "adopt" different children as needed.
Is this possible?
Perhaps the correct way to do this is something like:
const child = React.createClass({
//// etc
});
const str = ReactDOMServer.renderToString(<child />);
ReactDOMServer.renderToString(<HTMLParent child={str}/>);
回答1:
This is built in React
var Parent = React.createClass({
render: function(){
return (
<div>{ this.props.children }</div>
)
}
})
Usage:
ReactDOMServer.renderToString(<Parent><Children /><Parent>)
回答2:
This is perhaps one way to do it
const React = require('react');
module.exports = function (children) {
return React.createClass({
renderChildren: function () {
return children.map(function (item) {
var Comp = item.comp;
var props = item.props;
return (
<div>
<Comp {...props}/>
</div>
)
});
},
render: function () {
return (
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
<div>
{this.renderChildren()}
</div>
</body>
</html>
)
}
});
};
来源:https://stackoverflow.com/questions/36320590/server-side-rendering-with-react-composability-passing-child-component-to-p