Server-side rendering with React - composability => passing child component to parent

巧了我就是萌 提交于 2019-12-12 03:55:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!