为什么 styled-jsx 标签中的变量不起作用?
Why the variable in styled-jsx tag didn't work?
div
分量不固定,但sticky
变量为真。为什么?
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>
)
}
设置sticky
实际上不会更新您的组件。尝试使用反应挂钩来跟踪状态:
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);
}
}
div
分量不固定,但sticky
变量为真。为什么?
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>
)
}
设置sticky
实际上不会更新您的组件。尝试使用反应挂钩来跟踪状态:
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);
}
}