【问题标题】:How to render a child component inside a static component?如何在静态组件中渲染子组件?
【发布时间】:2018-01-24 11:29:41
【问题描述】:

我有以下反应组件:

            <HashRouter>
            <div className="App">

                {/* Static section */}
                <div>
                    <NavBar title="MyApp" />
                </div>

                {/* Dynamic section */}
                <div>

                    <Route path="//" component={HomePage} />
                    <Route path="/market" component={MarketPage}/>

                </div>

            </div>
        </HashRouter>

NavBar 组件期望渲染子组件,它们将根据 Ant 设计 component 表示网站内容。我的问题是如何在不重新渲染导航栏的情况下在导航栏组件内渲染我的子组件?我在导航栏中有一个 {this.props.children},但我不知道在不强制导航栏重新渲染的情况下注入道具的位置。

【问题讨论】:

  • 如果您将孩子作为道具传递,那么 NavBar 将重新渲染。
  • 传递孩子的方式是这样的&lt;NavBar title="MyApp"&gt; children &lt;/NavBar&gt;。然后你就可以在NavBar中访问this.props.children
  • 首先:你为什么要从道具中送出那些孩子?您可以将它们添加到NavBar 组件中吗?如果您真的必须从道具发送它们,那么您希望每次道具更改时都重新渲染 NavBar。

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

不。如果你想在B内部渲染组件A,并且你发送A作为B的prop,那么,B将会是每次他们的道具改变时重新渲染。

如果你想避免它,你不应该发送A作为一个prop,而只是在B中的一个包装组件中渲染它。

例如:

// Your NavBar
function NavBar() {
    // This component is not going to be re-rendered, due to is
    // not receiving the children components as props.
    // The childrens are going to be in <Wrapper>
    return (
        <div className="NavBar">
            Hello!<br>

            <Wrapper />
        </div>
    );
}

// Here you have to have a condition to show
// component `ChildA` or `ChildB`.
// You can do that switching with some Redux or Duix value
function Wrapper() {
    return (
        <div className="Wrapper">
            {
                somethingHappened ? <ChildA /> : <ChildB />;
            }
        </div>
    );
}

function ChildA() {
    return(...);
}

function ChildB() {
    return(...);
}

检查 Wrapper 组件是否应该监听一些 Redux (https://www.npmjs.com/package/react-redux) 或 Duix (https://www.npmjs.com/package/duix) 值以在 ChildAChildB 之间切换

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2016-12-21
    • 2018-06-23
    • 2020-10-15
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多