【问题标题】:Render one of the component that has inside another component according to state根据状态渲染具有另一个组件内部的组件之一
【发布时间】:2020-05-27 17:34:35
【问题描述】:

我遇到了根据条件渲染组件的问题。这两个组件都包含在应该呈现但不显示的确切组件内部。 它们都使用 Styled Components 设置样式。

在我的示例中,我想在单击另一个组件(页脚)时显示一个组件。 目前,我有这个工作:

    <footer className={cx(styles.footer, { [styles.hideFooter]: hide })}>
        <StyledAboutContainer>
          <About />
        </StyledAboutContainer>
    </footer>

我想将它转换为 Styled 组件方式,我很挣扎。 我试过这样做:

     <StyledFooterContainer hide={false}>
        {hide ? StyledHideFooter : StyledFooter}
        <StyledAboutContainer>
          <About />
        </StyledAboutContainer>
    </footer>

它们的 CSS 是:

export const StyledFooterContainer = styled.div`
 max-height: 0;
`;

export const StyledFooter = styled.footer`
 background: #EFF0F4;
 color: #6782A4;
 display: flex;
 flex-flow: column nowrap;
 flex-grow: 1;
 max-height: 150px;
 font-size: 10pt;
 transition: .7s ease;
`;

export const StyledHideFooter = styled.div`
 max-height: 0;
`;

谢谢。

【问题讨论】:

  • 看起来不像,看起来像别的东西。
  • 为什么不只是 not 在隐藏页脚时渲染页脚? !hide &amp;&amp; (&lt;footer .... ,还是使用三元和hide ? null : (&lt;footer ..... ?这是在 React 中选择性地呈现 UI 的更惯用的方式。唯一真正想到的原因是您是否需要始终保持该页脚安装。

标签: javascript reactjs styled-components


【解决方案1】:

您要在 return 语句之前确定要使用哪个页脚组件:

const MyComponent = () => {
  // Determine the footer component to use
  const FooterComponent = hide ? StyledHideFooter : StyledFooter;

  // Render FooterComponent
  return (
    <StyledFooterContainer>
      <FooterComponent>
        <StyledAboutContainer>
          <About />
        </StyledAboutContainer>
      </FooterComponent>
    </StyledFooterContainer>
  );
};

组件只是变量,所以你可以这样存储它们。

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2023-04-06
    • 2019-10-14
    • 1970-01-01
    • 2021-02-16
    • 2021-08-15
    • 1970-01-01
    • 2020-12-21
    相关资源
    最近更新 更多