数组中的值不加

时间:2019-06-18 10:17:43

标签: javascript reactjs

当您按下文档中的按钮(字符和数字)时,应将值添加到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>

1 个答案:

答案 0 :(得分:1)

存在问题

unsigned long long

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

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