Bjö*_*rth 15 javascript reactjs react-hooks
更新的问题:
如果我在滚动之前在输入字段中输入某些内容,则expanded道具将设置为 true - 正确
如果我向下滚动 - 展开设置为 false - 正确
如果我现在在输入字段中输入expanded内容仍然是false- 我希望再次expanded设置为true。
代码:
export default () => {
const [expanded, setExpanded] = useState(true)
let searchInput = React.createRef()
let scrollTopValue = 0;
function handleSearchInput() {
console.log(Boolean(searchInput.current.value.length))
setExpanded(Boolean(searchInput.current.value.length)) // first time true, don't get re triggered
}
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, []);
function handleScroll() {
setExpanded(scrollTopValue > document.documentElement.scrollTop)
scrollTopValue = document.documentElement.scrollTop
}
return (
<header>
{expanded? 'expanded': 'nope'}
<input role="search" ref={searchInput} onChange={handleSearchInput}></input>
</header>)
}
Run Code Online (Sandbox Code Playgroud)
在反应中更新状态不能保证同步调用。因此,当您在更改状态后立即调用 console.log(expanded) 时,它不会返回新状态。您的组件将在重新渲染时收到新状态。
你也可以参考这个博客 https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3
另一个参考:- useState set 方法不会立即反映更改
| 归档时间: |
|
| 查看次数: |
38462 次 |
| 最近记录: |