【问题标题】:Change Navbar Colour with State- Styled-Components使用状态样式组件更改导航栏颜色
【发布时间】:2022-01-25 20:40:42
【问题描述】:

我想通过 useState 钩子更改滚动时导航栏的颜色。

const Navbar = () => {

    const [colorChange, setColorchange] = useState(false);

    const changeNavbarColor = () =>{
       if(window.scrollY >= 38){
         setColorchange(true);
       }
       else{
         setColorchange(false);
       }
    };

    console.log(setColorchange)

    window.addEventListener('scroll', changeNavbarColor);

我正在尝试驱动以下样式的组件,如何控制背景:任何状态的道具?

const NavbarContainer = styled.div`
    width: 100%;
    height: 38px;
    background-color: red;
    margin-top: 10px;

    display: flex;
    justify-content: space-between;
    position: sticky;
    top:0;
    z-index: 1;
`;

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    你可以传递道具:

    
    <NavbarContainer bg={yourDynamicColor}>
     ...
    </NavbarContainer>
    
    const NavbarContainer = styled.div`
        background-color: ${props => props.bg};
        // you can write any javascript, e.g:
        color: ${({bg}) => bg === 'white' : 'black' : 'white'}
    `;
    

    【讨论】:

      【解决方案2】:
      const NavbarContainer = styled.div`
          width: 100%;
          height: 38px;
          background-color: ${props => props.colorChange ? "red" : "blue"};
          margin-top: 10px;
      
          display: flex;
          justify-content: space-between;
          position: sticky;
          top:0;
          z-index: 1;
      `;
      

      【讨论】:

        【解决方案3】:

        我认为最好的方法是根据状态更新组件的 className。 还要在 useEffect 中初始化你的 eventListener 并在组件卸载时将其删除。

        import React, { useEffect, useState } from 'react';
        
        const Navbar = () => {
            const [colorChange, setColorchange] = useState(false);
        
            const changeNavbarColor = () => {
               if(window.scrollY >= 38){
                 setColorchange(true);
               }
               else{
                 setColorchange(false);
               }
            };
        
            useEffect(() => {
                window.addEventListener('scroll', changeNavbarColor);
                return () => {
                    window.removeEventListener('scroll', changeNavbarColor);
                }
            }, [])
            
            return (
                <div className={colorChange ? 'colorBlack' : 'colorWhite'}>
                    <p>Your navbar</p>
                </div>
            )
        }
        
        export default Navbar;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-07
          • 2020-01-21
          • 2018-02-06
          • 2013-03-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多