我正在尝试滚动到顶部按钮。我完成了滚动到顶部部分,但我正在努力显示部分。我在这里错过了什么?
showActionWhenPosition
返回正确的值,但我的"显示"不起作用。这是我得到的。
import React, { useEffect, useState } from 'react'
import ArrowDown from "components/svg/ArrowDown"
import { injectIntl } from "react-intl"
import { useMediaQuery } from 'react-responsive'
import { TO_MEDIUM } from 'core/ui/breakpoints'
const TheToTop = ({ intl }) => {
const [windowHeight, setWindowHeight] = useState(0)
const toMedium = useMediaQuery({
query: TO_MEDIUM
})
const scrollAction = () => {
const htmlElement = document.querySelector('html')
htmlElement.scrollTo({
top: 0
})
}
const showActionWhenPosition = () => {
const scrollPosition = window.scrollY
console.log(scrollPosition)
if (scrollPosition > windowHeight) {
console.log('yes')
} else {
console.log('no')
}
return scrollPosition > windowHeight
}
useEffect(() => {
setWindowHeight(window.innerHeight / 2)
}, [])
useEffect(() => {
document.addEventListener('scroll', showActionWhenPosition)
return () => {
document.removeEventListener('scroll', showActionWhenPosition)
}
})
return (
<React.Fragment>
{(toMedium && showActionWhenPosition()) && <button className="to-top" onClick={() => scrollAction()}>
<ArrowDown className="to-top__action-svg-arrow" />
</button>}
</React.Fragment>
)
}
export default injectIntl(TheToTop)
你应该使用状态。例如
import React, { useEffect, useState } from 'react'
import ArrowDown from "components/svg/ArrowDown"
import { injectIntl } from "react-intl"
import { useMediaQuery } from 'react-responsive'
import { TO_MEDIUM } from 'core/ui/breakpoints'
const TheToTop = ({ intl }) => {
const [windowHeight, setWindowHeight] = useState(0)
const [shouldShow, setShouldShow] = useState(false)
const toMedium = useMediaQuery({
query: TO_MEDIUM
})
const scrollAction = () => {
const htmlElement = document.querySelector('html')
htmlElement.scrollTo({
top: 0
})
}
const showActionWhenPosition = () => {
const scrollPosition = window.scrollY
console.log(scrollPosition)
if (scrollPosition > windowHeight) {
setShouldShow(true)
} else {
setShouldShow(false)
}
}
useEffect(() => {
setWindowHeight(window.innerHeight / 2)
}, [])
useEffect(() => {
document.addEventListener('scroll', showActionWhenPosition)
return () => {
document.removeEventListener('scroll', showActionWhenPosition)
}
})
return (
<React.Fragment>
{(toMedium && shouldShow ) && <button className="to-top" onClick={() => scrollAction()}>
<ArrowDown className="to-top__action-svg-arrow" />
</button>}
</React.Fragment>
)
}
export default injectIntl(TheToTop)
它不起作用的原因是因为页面没有重新呈现