【发布时间】:2018-10-28 22:37:10
【问题描述】:
我正在尝试在 React 中创建一个屏蔽输入(不使用屏蔽输入库)。我的问题是我无法使用 onchange 属性访问 e.key - 它只是给我未定义,所以我使用 onKeyDown 代替 - 这是有效的,但我在控制台中收到警告:
“警告:失败的道具类型:您为没有onChange处理程序的表单字段提供了value道具。这将呈现一个只读字段。如果该字段应该是可变的,请使用defaultValue。否则,设置onChange 或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 $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;
提前感谢您的任何指点!
【问题讨论】:
-
输入字段应该如何工作?我显然不应该使用箭头键。我也进不去
$1.20 -
是的,对不起,我仍在努力解决零和箭头键等边缘情况,但它应该在值的末尾添加数字并移动小数点,所以对于例如,如果您输入 123,则输入将显示为“$1.23”,或者如果您输入“12”,它将显示为“$0.12”,或者如果您输入 12345,它将显示为“$123.45”等
-
这是我的看法:codesandbox.io/s/3rwywn57q 我不会把它作为答案发布,因为我不太喜欢它。
标签: javascript reactjs input onchange maskedinput