我正在尝试在 React 中创建一个掩码,但是 onKeyPressed
它不会因退格键或删除而触发。它不允许删除输入。
这是我的代码:
export default class InputField extends React.Component {
constructor(props) {
super(props);
this.state = { text: this.props.text };
this.onKeyPress = this.onKeyPress.bind(this);
}
onKeyPress(event) {
console.log(event.key);
var mask = this.props.mask;
var currentText = this.state.text || "";
var invalidButtonPress = false;
switch (mask) {
case "number":
if ("0123456789".indexOf(event.key) > -1) {
this.setState({ text: currentText + event.key });
} else {
invalidButtonPress = true;
}
break;
default:
break;
}
if (invalidButtonPress) {
// allow for arrow keys, tab and backspace.. but if none of those and invalid reset
this.setState({ text: currentText }); // Reset back to original text
}
}
render() {
<Input
type={this.props.type || "text"}
value={this.state.text}
mask={this.props.mask}
onKeyPress={this.onKeyPress}
>
...
}
}
我尝试过 onKeyDown
和 OnKeyUp
,它们确实检测退格键,但这些事件我无法通过 this.setState( {})
。
最佳答案
I have tried onKeyDown and OnKeyUp, which do detect backspace, but these events I am unable to effect the value on the input by this.setState({})
React 允许您混合和匹配这些事件。因此,您可以保留 onKeyPress
用于添加到输入中,并使用 onKeyDown
或 onKeyUp
进行删除。
关于javascript - ReactJs输入: onKeyPressed does not fire for backspace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858776/