我正在寻找电话号码格式。当用户输入号码时。在输入字段中。它应该是这样的。 (123)-111-1233 提前谢谢。我正在分享我的工作。我应该使用onKeyDown还是onKeyPress。它不完整的代码,但我给和Idea.where我必须添加格式电话号码的功能
Class FormInput extends React.Component {
constructor() {
super();
this.state = {
phone: '',
}
this.handleKeyPress=this.handleKeyPress.bind(this);
}
phoneFormat(input){
// Strip all characters from the input except digits
input = input.replace(/\D/g,'');
// Trim the remaining input to ten characters, to preserve phone number format
input = input.substring(0,10);
// Based upon the length of the string, we add formatting as necessary
var size = input.length;
if(size == 0){
input = input;
}else if(size < 4){
input = '('+input;
}else if(size < 7){
input = '('+input.substring(0,3)+') '+input.substring(3,6);
}else{
input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10);
}
return input;
}
handleKeyPress(event){
this.setState({});
}
<input name='phone' type='text' ref="input" placeholder='(___)-___-____' value={this.state.phone} onKeyDown={this.handleKeyPress} onChange={this.handleChange}/>
}