簡體   English   中英

React中屏蔽輸入的onChange問​​題

[英]Problem with onChange for Masked Input in React

我正在嘗試在React中創建一個屏蔽輸入(不使用屏蔽輸入庫)。 我的問題是我無法使用onchange道具訪問e.key-它只是給我未定義,所以我改用了onKeyDown-這是可行的,但是我在控制台中收到一條警告,內容是:

“警告:道具類型失敗:您為沒有onChange處理程序的表單字段提供了一個value道具。這將呈現一個只讀字段。如果該字段是可變的,請使用defaultValue 。否則,請設置onChangereadOnly 。”

我試過使用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 $0.01 ... $0.12 ... $1.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 || "$0.00"} //value is $0.00 to start, then it is whatever the input is
          onKeyDown={this.getKey}/>
        </header>
      </div>
    );
  }
}

export default App;

預先感謝您提供任何指導!

在React Github Repo的一個相關問題上進行了長時間的討論。 並且還沒有提供優雅的解決方案。

目前消除此警告的最簡單解決方案是,按照本文中的建議, 輸入元素中添加一個單獨的虛擬onChange道具( onChange={() => {}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM