【问题标题】:Switch theme based images on scroll in React App with Styled Components使用样式化组件在 React App 中滚动切换基于主题的图像
【发布时间】:2020-10-17 20:18:32
【问题描述】:

我有一个带有 styled components 的 Next.js 应用程序,它具有基于用户访问网站的时间的 day/night 模式(即标准/暗模式)。到目前为止,一切都很好。在某些页面上,虽然我有一个黑暗的英雄,所以无论当前激活的主题是day 还是night,导航都需要是浅色的。除此之外,导航非常复杂,并且使用了多个嵌套元素、边框和图标。

我实现此目的的方式是拥有const [navBarStyle, setNavBarStyle] = useState('light') 的状态,一旦用户到达某个滚动位置,该状态就会发生变化。 在我的样式组件中,我根据道具和状态进行更新,例如

  border-width: 1px;
  border-style: solid;
  border-color: ${
  props => props.hasDedicatedHeroNavBar && props.currentNavBarStyle === 'light' ? ThemeSettings.colors.light
        : props.hasDedicatedHeroNavBar && props.currentNavBarStyle === 'default' ? ThemeSettings.mainColor
        : ThemeSettings.mainColor
      };

正如您现在在这里看到的,我不得不将边框属性分成多行,因为我无法在模板字符串中传递主题设置,因为它返回一个函数: background-image: url(function(props) { return getThemeValue(name,props,values); });(复制自我的浏览器开发面板)。

对于我可以拆分的设置(例如边框)很容易做到这一点,但我如何才能为背景图像做到这一点,因为以下方法不起作用:

  background-image: ${
        props => props.hasDedicatedHeroNavBar && props.currentNavBarStyle === 'light' ? `url('/images/account-icon-light.svg')`
        : props.hasDedicatedHeroNavBar && props.currentNavBarStyle === 'default' ? `url(${ThemeSettings.accountIcon})`
        : `url(${ThemeSettings.accountIcon})`
  };

【问题讨论】:

    标签: reactjs next.js styled-components


    【解决方案1】:

    您可以将抽象利用到组件级别,您可以在其中为每个图标或其他组件指定样式

    const UniversalIconImg = (props) => {
      return props.hasDedicatedHeroNavBar && props.currentNavBarStyle === "light" ? (
        <IconLight {...props} />
      ) : props.hasDedicatedHeroNavBar && props.currentNavBarStyle === "default" ? (
        <IconDefault {...props} />
      ) : (
        <IconElse {...props} />
      );
    };
    
    const IconLight = styled.div`
      background-image: url("/images/account-icon-light.svg");
    `;
    
    const IconDefault = styled.div`
      background-image: url("${ThemeSettings.accountIcon}");
    `;
    
    ...
    

    【讨论】:

    • 谢谢你,虽然不是很明显!
    猜你喜欢
    • 2017-11-20
    • 2020-04-17
    • 2017-08-05
    • 2019-07-12
    • 2016-05-12
    • 2023-03-10
    • 2021-07-17
    • 2017-03-14
    相关资源
    最近更新 更多