React.js 如何在组件内部渲染组件?

新手上路,请多包涵

我卡住了。我在单独的文件上有几个单独的组件。如果我像下面这样在 main.jsx 中渲染它们:

 ReactDOM.render(<LandingPageBox/>, document.getElementById("page-landing"));
ReactDOM.render(<TopPlayerBox topPlayersData={topPlayersData}/>, document.getElementById("wrapper profile-data-wrapper"));
ReactDOM.render(<RecentGamesBox recentGamesData={recentGamesData}/>, document.getElementById("history wrapper"));

一切正常,但我想知道这是否是一个好习惯?也许可以做一些像只有一个 ReactDom.render 这样的事情:

 ReactDOM.render(<LandingPageBox recentGamesData={recentGamesData} topPlayersData={topPlayersData}/>, document.getElementById("page-landing"));

我尝试了不同种类的 LandingPageBox 变体以某种方式包含其他两个组件,但没有成功。它们有时会呈现在页面之外等等。我认为它应该看起来像这样:

 import React from 'react';
import RecentGames from '../RecentGames/RecentGames.jsx';
import TopPlayers from '../TopPlayers/TopPlayers.jsx';
import PageTop from './PageTop.jsx';
import PageBottom from './PageBottom.jsx';

class LandingPageBox extends React.Component {
    render() {
        return (
            <body className="page-landing">
                <PageTop>
                     <TopPlayers topPlayersData={this.props.topPlayersData} />
                </PageTop>
                <PageBottom>
                        <RecentGames recentGamesData=    {this.props.recentGamesData}/>
                    </PageBottom>
                </body>
            );
        }
    }

export default LandingPageBox;

但是这段代码只渲染了 PageTop 和 PageBottom,没有播放器或游戏组件。

所以我的问题是,如何设置 LandingPageBox 文件,以便 TopPlayers 组件在 PageTop 组件内呈现,而 RecentGames 组件在 PageBottom 组件内呈现?谢谢你。

原文由 R. Vait 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 365
2 个回答

在你的例子中

return (
        <body className="page-landing">
            <PageTop>
                 <TopPlayers topPlayersData={this.props.topPlayersData} />
            </PageTop>
            <PageBottom>
                 <RecentGames recentGamesData=    {this.props.recentGamesData}/>
            </PageBottom>
        </body>
       );

正如您已经发现的那样,React 只会呈现顶级自定义组件 PageTopPageBottom 。其他组件( TopPlayersRecentGames嵌套 在这些组件中。这意味着什么? React 不只是显示那些嵌套的组件,因为它不知道如何执行此操作。相反,所有渲染都必须由外部组件 PageTopPageBottom 。 React just passes the nested components to them ( PageTop gets TopPlayers , PageBottom gets RecentGames ) in this.props.children .现在 由外部组件 决定如何处理这些嵌套组件。在您的示例中,您将修改 PageTopPageBottom 组件以使用 {this.props.children} 以适当的方式显示它们的嵌套组件。

原文由 Nicole 发布,翻译遵循 CC BY-SA 3.0 许可协议

你说的对。您可以根据需要使用任意数量的嵌套组件。它是 React 中的主要概念之一。您可以在 this.props.children 中访问它们。像这样做:

 var Parent = React.createClass({
  render: function() {
    return <div>{this.props.children}</div>;
  }
});

ReactDOM.render(
  <Parent>
    <Child/>
    <Child/>
  </Parent>,
  node
);

在这里阅读更多 - https://facebook.github.io/react/docs/multiple-components.html

在这里 - http://buildwithreact.com/article/component-children

原文由 Dmitriy Nevzorov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题