使用正则表达式实时反应本机

Use Regular expression react native on real time

我是否在我的公司使用 React-Native 和 TypeScript 启动了一个项目,我们在 pt-br 的掩码中遇到了问题...我不能在 npm 代码中使用默认库,因为不是灵活的代码,现在我真的想使用正则表达式来转换状态和接收掩码,这里我们使用掩码 phone 像这样 (41) 9 9887-7665 传递一个值 (41998877665) 和 return带面具,我在 js 中尝试了这么多代码但没有用...

我真的只是想知道,如何在 react-native 中使用正则表达式。

  _addMaskPhoneBr(phone: any){  //this is my function to add mask into my screen
    phone = phone.replace(/^[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-/\s.]?[0-9]{4}$/); //mask have i try to apply, i know this will not return a spected result, but after i can use i'll fixit to a mask pt br

    this.setState({ phone: phone }); // set state to reload value into textInput {stateVariable: setValu}
 }

用户输入的组件 phone...

<View style={viewEditStyle}>
 <TextField 
  label={I18n.t("proposalDetail.phone")} 
  value={this.state.phone} //this reload value from state
  keyboardType="numeric"
  onChangeText={value => this._addMaskPhoneBr(value)} // this set function a value to add mask
  maxLength={16}
 />

Pic from Console.log returns

感谢大家的帮助!

我用这段代码修复了吗:

  _addMaskPhoneBr(phone: string){  
try {
  phone =  phone.replace(/[^\d]+/g,'');
  this.setState({ phone: phone });
  if(phone.length == 10){
    phone = (phone.length > 1 ? "(" : "")+phone.substring(0, 2) + (phone.length > 2 ? ")" : "")+(phone.length > 2 ? " " : "") + phone.substring(2,6) + (phone.length > 3 ? "-" : "") + phone.substring(6, 10);
  } else {
    phone = (phone.length > 1 ? "(" : "")+phone.substring(0, 2) + (phone.length > 2 ? ")" : "")+(phone.length > 2 ? " " : "") + phone.substring(3,2) + (phone.length > 3 ? " " : "") + phone.substring(3, 7) + (phone.length > 7 ? "-" : "") + phone.substring(7, 12);
  }
} catch(e){
  this.setState({ phone: phone });
}
this.setState({ phone: phone });

}