简体   繁体   中英

Why the variable in styled-jsx tag didn't work?

The div component is not fixed, but the sticky variable is true. Why?

import React, { useEffect } from 'react'

export default function Navbar(props) {

  const DESKTOP_Y = 250
  const MOBILE_Y = DESKTOP_Y / 2

  let sticky = false

  const handleScroll = () => {
    console.log(window.innerWidth + ' ' + window.scrollY + ' ' + sticky)
    if (window.innerWidth > 850) {
      if (window.scrollY > DESKTOP_Y) {
        sticky = true
      } else {
        sticky = false
      }
    } else if (window.innerWidth < 850) {
      if (window.scrollY > MOBILE_Y) {
        sticky = true
      } else {
        sticky = false
      }
    }
  }

  useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [])

  return (
    <nav>
      <div>Pozdro</div>
      <style jsx>
        {`
          div {
            ${sticky ? 'position: fixed' : ''}
          }
        `}
      </style>
    </nav>
  )
}

Setting sticky will not actually update your component. Try using react hooks to keep track of state:

sticky, setSticky = useState(0);
const handleScroll = () => {
console.log(window.innerWidth + ' ' + window.scrollY + ' ' + sticky)
if (window.innerWidth > 850) {
  if (window.scrollY > DESKTOP_Y) {
    setsticky(true);
  } else {
    setsticky(false);
  }
} else if (window.innerWidth < 850) {
  if (window.scrollY > MOBILE_Y) {
       setsticky(true);
  } else {
       setsticky(false);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM