简体   繁体   English

使用React进行服务器端渲染-可组合性=>将子组件传递给父组件

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

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. 但是我正在寻找的是父React组件能够根据需要“采用”不同子组件的模式。

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}/>);

This is built in React 这是内置在React中

var Parent = React.createClass({

   render: function(){

      return (
        <div>{ this.props.children }</div>
      )
   } 

})

Usage: 用法:

 ReactDOMServer.renderToString(<Parent><Children /><Parent>)

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>

            )

        }

    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM