我的状态发生变化,但在useEffect滚动时不会添加类

时间:2019-09-25 13:06:50

标签: reactjs react-hooks

当页面下降320 px(全部带有useEffect和useState)时,我需要更改JSX元素的背景。到目前为止,我设法更改了状态,但没有添加其他颜色的背景类。

  

我正在使用NODE 8.9.3,NPM 5.5.1和REACT JS 16.9.0

import React, { useEffect, useState } from 'react'

import { useScrollYPosition } from 'react-use-scroll-position'

import { Container } from '../../styles/Container'
import { ContainerCustom, HeaderComp } from './styles'

import Logo from './Logo'
import Menu from './Menu'
import Icons from './Icons'

const ContainerBox = () => {
  return (
    <ContainerCustom fluid>
      <Container>
        <HeaderComp>
          <Logo />
          <Menu />
          <Icons />
        </HeaderComp>
      </Container>
    </ContainerCustom>
  )
}

const Header = () => {
  const [back, setBack] = useState(0)

  const handleBackState = () => {
    const scrollY = window.scrollY
    if (scrollY > 320) {
      setBack(1)
      console.log(`Estado: ${back}`)
    } else {
      setBack(0)
      console.log(`Estado após remover: ${back}`)
    }
  }

  useEffect(() => {
    window.addEventListener('scroll', handleBackState)
    return () => {
      window.removeEventListener('scroll', handleBackState)
    }
  }, [handleBackState])
  return <ContainerBox className={back === 1 ? 'removeGradients' : ''} />
}
  

在控制台上,输出状态为0,在320之后,删除后为State:   1

1 个答案:

答案 0 :(得分:1)

并非每个组件在DOM中都具有表示形式。您需要将className应用于实际上具有相应DOM元素的组件,以使样式生效:

// className will not affect the DOM as this component does not render a DOM element
const WrappingComponent = ({className}) => (
    <WrappedComponent className={className} />
);

// this className will be applied to the div in the DOM
const WrappedComponent = ({className}) => (
    <div className={className}>Content here</div>
);