Javascript 不使用onChange更新状态
更新问题: 如果我在滚动之前在输入字段中键入了一些内容,则Javascript 不使用onChange更新状态,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,更新问题: 如果我在滚动之前在输入字段中键入了一些内容,则扩展的属性将设置为true-correct 如果我向下滚动-扩展设置为false-correct 如果我现在在输入字段中键入的内容expanded仍然是false-我希望expanded再次设置为true 代码: 导出默认值()=>{ const[expanded,setExpanded]=useState(true) 让searchInput=React.createRef() 设scrollTopValue=0; 函数handleSe
扩展的属性将设置为true-correct
如果我向下滚动-扩展设置为false-correct
如果我现在在输入字段中键入的内容expanded
仍然是false
-我希望expanded
再次设置为true
代码:
导出默认值()=>{
const[expanded,setExpanded]=useState(true)
让searchInput=React.createRef()
设scrollTopValue=0;
函数handleSearchInput(){
log(布尔值(searchInput.current.value.length))
setExpanded(Boolean(searchInput.current.value.length))//第一次为true时,不重新触发
}
useffect(()=>{
window.addEventListener('scroll',handleScroll)
return()=>window.removeEventListener('scroll',handleScroll)
}, []);
函数handleScroll(){
setExpanded(scrollTopValue>document.documentElement.scrollTop)
scrollTopValue=document.documentElement.scrollTop
}
返回(
{扩展?'expanded':'nope'}
)
}
在react中更新状态不保证同步调用。因此,当您在更改状态后调用console.log(expanded)时,它不会返回新状态。组件将在重新渲染时接收新状态
你也可以参考这个博客
另一参考:-
我没有看到更新。你是说{expanded?'expanded':'nope'}
不能按预期工作吗?你发布的代码中没有问题。更新的问题,希望我能更好地解释我自己。如果你有问题没有解决,我会解开问题并尝试回答。但从我看来,没有问题。更改和滚动处理程序都会按预期更新状态。这无法复制,如果我在现在扩展的输入字段中键入的内容仍然为false。感谢您提供的代码,我肯定还有一些我不知道的错误。谢谢你抽出时间,我会看看我的管道有什么不同,不客气。如果你能想出一个可以复制这个问题的例子,请随时打电话给我。
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>)
}