typescript 如何在React上按下键(“Enter”)后清除输入字段?

4xrmg8kj  于 2023-01-31  发布在  TypeScript
关注(0)|答案(1)|浏览(228)

我正在开发一个小应用程序,在该程序中,我为两个不同的人在输入金额后显示他们的余额。例如,如果Alex的当前余额是100,我在收入字段中输入一个数字,则余额增加。当您在支出字段中输入一个数字时,余额减少。第二个人也是如此。我尝试在按下回车键后清除字段。
App.tsx

import React, { useState } from 'react'
import './App.css'

import { Header } from './components/Header'
import { Balance } from './components/Balance'

function App() {
  const [alexBalance, setAlexBalance] = useState(0)
  const [yuliaBalance, setYuliaBalance] = useState(0)

  const [value, setValue] = useState('')

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value)
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {

    if (e.key === 'Enter') {
      calcResult(e.currentTarget.id, value)
      // document.querySelectorAll('input').forEach(input => (input.value = ''))
    }
  }

  const calcResult = (id: string, val: string) => {
    switch (id) {
      case 'deposit-Alexander':
        setAlexBalance(alexBalance + Number(val))
        break
      case 'withdraw-Alexander':
        setAlexBalance(alexBalance - Number(val))
        break
      case 'deposit-Yulia':
        setYuliaBalance(yuliaBalance + Number(val))
        break
      case 'withdraw-Yulia':
        setYuliaBalance(yuliaBalance - Number(val))
        break
    }
  }

  return (
    <div className='App'>
      <Header />
      <div className='wrapper flex flex-wrap justify-around'>
        <Balance user='Alexander' onChange={handleChange} onKeyDown={handleKeyDown} balance={alexBalance}
        />
        <Balance user='Yulia' onChange={handleChange} onKeyDown={handleKeyDown} balance={yuliaBalance}
        />
      </div>
    </div>
  )
}

export default App

Balance.tsx

import { Input } from './Input'
import React from 'react'

type BalanceProps = {
  user: string
  balance: any
  onKeyDown: React.KeyboardEventHandler
  onChange: React.ChangeEventHandler<HTMLInputElement>
  
}

export const Balance = (props: BalanceProps) => {
  return (
    <div className='balance mb-8 mt-8 border-2 shadow rounded py-8 px-8 w-4/6 max-w-3xl'>
      <div className='balance__header flex flex-col'>
        <span className=''>
          {props.user}'s current balance: {props.balance}
        </span>
        <span>Enter a value</span>
        <Input
          id={`deposit-${props.user}`}
          name={`add-${props.user}`}
          placeholder='+ income'
          onKeyDown={props.onKeyDown}
          onChange={props.onChange}
        />
        <Input
          id={`withdraw-${props.user}`}
          name={`sub-${props.user}`}
          placeholder='- expense'
          onKeyDown={props.onKeyDown}
          onChange={props.onChange}
        />
      </div>
    </div>
  )
}

Input.tsx

import { ChangeEventHandler, KeyboardEventHandler } from 'react'

type InputProps = {
  placeholder: string
  id: string
  name: string
  onKeyDown: KeyboardEventHandler<HTMLInputElement>
  onChange: ChangeEventHandler
}

export const Input = (props: InputProps) => {

  return (
    <div>
      <input
        type='text'
        id={props.id}
        name={props.name}
        className='input shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline text-center w-4/6 mt-2 mb-2'
        onKeyDown={props.onKeyDown}
        onChange={props.onChange}
        placeholder={props.placeholder}
      />
    </div>
  )
}

我试过这个...

const handleKeyDown = (e: React.KeyboardEvent) => {

    if (e.key === 'Enter') {
      calcResult(e.currentTarget.id, value)
      document.querySelectorAll('input').forEach(input => (input.value = ''))
    }
  }

这对我很有效,但是,正如我所知,这不是最佳实践。我希望得到一个使用状态的解决方案。我不希望为每个输入使用单独的状态。非常感谢

vc6uscn9

vc6uscn91#

你只要在点击回车键时将状态设置为空就可以了,所以不要在e.key==='Enter'块中添加注解代码,而是将你想要的状态设置为空。

setAlexBalance(0)
setYuliaBalance(0)
setValue('')

相关问题