【问题标题】:How can i change a navbar logo img, background and links color?如何更改导航栏徽标图像、背景和链接颜色?
【发布时间】:2020-05-28 08:59:00
【问题描述】:

我有一个 Preact 项目,我想在开始向下滚动时更改导航栏背景颜色、img src 和链接颜色。我怎样才能做到这一点?我是 Preact 的新手,有点困惑,我只是将一个类命名为 class={style.classname}。 感谢您的帮助。

【问题讨论】:

    标签: preact


    【解决方案1】:

    对于 scroll 事件,您需要注册 window 对象,这是您组件之外的关注点。所以如果使用基于类的组件,你可以在使用函数式组件时使用适当的回调处理程序或使用useEffect钩子注册外部事件。

    例如,在使用功能组件时,您可以:

    import { h } from 'preact';
    import { useEffect } from 'preact/hooks';
    
    function function addEvent(node, eventName, callback) {
    
      node.addEventListener(eventName, callback);
    
      // Note the use of de-registration/unsubscribe function
      return () => node.removeEventListener(eventName, callback);
    }
    
    
    export function AppComp(props) {
    
      // The dependency array is empty since it doesn't depend on anything.
      useEffect(() => {
        const deregister = addEvent(window, 'scroll', () => {
          // Your logic on scroll.
        });
    
        // Remove the event subscription when component is destroyed
        return () => deregister();
      }, []);
    
      return (
        <div>Hello</div>
      );
    }
    

    注意addEvent函数的使用。它返回一个注销函数,可用于移除附加事件,通常是在组件被销毁以确保没有内存泄漏或不需要的状态时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2015-07-22
      • 2015-05-27
      • 2021-09-12
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多