我正在制作一个可以控制输入的应用。我想要一个特定的输入只接受数字而且我已经实现了它,但它不需要小键盘输入,因为它将它们作为字母(代码范围是96到105)
这是输入:
<input onKeyDown = {(e) => this.handleChange(e)} type="text" value = {this.state.inputValue} />
我的功能:
handleChange(e){
let value = this.state.inputValue;
if(e.keyCode >= 48 && e.keyCode <= 57 && value.length < 4)
{
this.setState(
{
inputValue: value + String.fromCharCode(e.keyCode)
}
);
}
else if(e.keyCode == 8)
{
this.setState(
{
inputValue: value.substring(0, value.length - 1)
}
);
}
}
答案 0 :(得分:0)
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
inputValue: null,
}
}
handleChange(e) {
let value = this.state.inputValue
if (((e.keyCode >= 48 && e.keyCode <= 57) ||
(e.keyCode >= 96 && e.keyCode <= 105)) &&
value &&
value.toString().length < 4
) {
this.setState({
inputValue: parseInt(value + String.fromCharCode(e.keyCode), 10)
})
} if (e.keyCode >= 48 && e.keyCode <= 57 && !value) {
this.setState({
inputValue: parseInt(String.fromCharCode(e.keyCode), 10)
})
} else if (e.keyCode === 8) {
if(value) {
const stringSliced = value.toString().substring(0, value.toString().length - 1)
this.setState({
inputValue: stringSliced === ""
? null
: parseInt(stringSliced, 10)
})
}
}
}
render() {
console.log("this.state", this.state)
return (
<input
onKeyDown={
e => this.handleChange(e)
}
type="text"
value={
this.state.inputValue
}
/>
)
}
}
ReactDOM.render(<Test />, document.getElementById("root"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div>
&#13;
这可能会有所帮助!!!