我试图在不使用库的情况下在React中创建输入掩码,但是当我尝试删除输入文本时,它会堆积在')'
上。
这是我到目前为止尝试过的:
class Ex1 extends React.Component {
constructor(props) {
super(props);
this.state = {
number: "",
masked: ""
};
this.handleChange = e => {
let number = e.target.value;
number = number.replace(/\D/g, "");
let len = number.length;
let temp = "";
if (len < 3) {
temp = "(" + number + " )";
} else if (len == 3) {
temp = "(" + number + ")";
} else if (len > 3 && len < 7) {
temp = "(" + number.substring(0, 3) + ")" + number.substr(3);
} else if (len > 6 && len < 11) {
temp =
"(" +
number.substring(0, 3) +
")" +
number.substring(3, 6) +
"-" +
number.substr(6);
} else {
temp = number;
}
this.setState({
number,
masked: temp
});
};
}
render() {
return (
<div>
<input
type="tel"
onChange={this.handleChange}
value={this.state.masked}
/>
{this.state.number && <h3>{`Value: +1${this.state.number}`}</h3>}
</div>
);
}
}
ReactDOM.render(<Ex1 />, document.querySelector("#app"));