React 中屏蔽输入的 onChange 问题

Problem with onChange for Masked Input in React

我正在尝试在 React 中创建屏蔽输入(不使用屏蔽输入库)。我的问题是我无法使用 onchange 道具访问 e.key——它只是给我未定义,所以我改用 onKeyDown——这是有效的,但我在控制台中收到一条警告:

"Warning: Failed prop type: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly."

我曾尝试使用 keyDown 获取密钥,然后使用 onChange 函数屏蔽输入,但它总是比应有的位置晚一个字符。

这就是我的代码到目前为止的样子,如果有任何可以解决此问题的提示等,我将不胜感激。

class App extends Component {
  state={
    input: "",
    acc: "", //this is an accumulator I'm using to hold the unmasked version of the input
    currentKey: ""
  }

  getKey = (e) => {
    if(e.key === "Backspace"){ //removes last letter on backspace
      const lastLetterRemoved = this.state.acc.substr(0,this.state.acc.length-1)
      this.setState({acc: lastLetterRemoved, input: this.mask(lastLetterRemoved)})
    } else {
      let currentChar;
      if(!Number(e.key)){//ignores non-numeric characters
          currentChar = ""
      } else {
        currentChar=e.key //adds current key to accumulator, masks it and sets input value
        const currentAcc = this.state.acc + currentChar
        this.setState({acc: currentAcc, input: this.mask(currentAcc)})
      }
    }
  }

//function to mask the input as the user types the Numbers should appear
//already formatted as an amount of currency
//example: inputting 123 would behave like this [=10=].01 ... [=10=].12 ... .23
  mask = (num) => {
    let dollars;
    let cents;
    if(num<10){
      dollars = "0"
      cents = `0${num}`
    } else {
      dollars=Math.floor(num/100)
      cents=num%100
    }
    return `$${dollars}.${cents}`
  }


  render() {
    return (
      <div className="App">
        <header className="App-header">
          <input 
          value={this.state.input || "[=10=].00"} //value is [=10=].00 to start, then it is whatever the input is
          onKeyDown={this.getKey}/>
        </header>
      </div>
    );
  }
}

export default App;

提前感谢您的指点!

related issue on React Github Repo 正在进行长时间的对话。并且目前还没有提供优雅的解决方案

目前删除此警告的最简单解决方案是,按照建议向输入元素添加一个单独的虚拟 onChange 道具 (onChange={() => {}}) in this post