gpt4 book ai didi

javascript - 数组中的值不相加

转载 作者:行者123 更新时间:2023-11-30 19:28:50 25 4
gpt4 key购买 nike

当您在文档中按下按钮(字符和数字)时,应将值添加到 filterName,但只有最后一次按下才会添加。我不明白我做错了什么。

ReactJS v.16.8.6

const App = () => {
const [filterName, setFilterName] = React.useState('')

React.useEffect(() => {
document.addEventListener('keydown', handleKeyPress)
return () => {
document.removeEventListener('keydown', handleKeyPress)
}
}, [])

React.useEffect(()=>{
console.log(filterName)
})

const handleKeyPress = (event) => {
//backspace (remove last typed symbol)
if (event.keyCode === 8) {
setFilterName(
filterName
.split('')
.filter((f, index) => index !== filterName.length - 1)
.join('')
)
}
//chars or diggits
if (
(event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 65 && event.keyCode <= 90) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode === 32
) {
setFilterName([...filterName.split(''), event.key].join(''))
}
}
return <div> {filterName} </div>
}

ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>

<div id="root"></div>

最佳答案

问题出在

React.useEffect(() => {
document.addEventListener('keydown', handleKeyPress)
return () => {
document.removeEventListener('keydown', handleKeyPress)
}
}, [])

事件监听器应该在没有输入的情况下像这样添加和删除:

React.useEffect(() => {
document.addEventListener('keydown', handleKeyPress)
return () => {
document.removeEventListener('keydown', handleKeyPress)
}
})

关于javascript - 数组中的值不相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com