Javascript 带React的输入掩蔽
如何使用react进行输入屏蔽: 这就是我目前所拥有的。我似乎无法获得正确更新的值,我还希望光标在输入中单击时位于开头。我有点被困在这里了 输入的预期输出:类似于Javascript 带React的输入掩蔽,javascript,reactjs,Javascript,Reactjs,如何使用react进行输入屏蔽: 这就是我目前所拥有的。我似乎无法获得正确更新的值,我还希望光标在输入中单击时位于开头。我有点被困在这里了 输入的预期输出:类似于0./=>0 9/0.=>0 9/0 9 import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state
0./
=>0 9/0.
=>0 9/0 9
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
};
this.update = this.update.bind(this);
}
update(e) {
e.preventDefault();
const formatString = '_ _ / _ _';
const newString = `${e.target.value}${formatString.slice(
e.target.value.length
)}}`;
this.setState({ [e.target.name]: newString });
}
render() {
return (
<div>
<input
type="text"
onChange={this.update}
name="inputValue"
value={this.state.inputValue}
onFocus={() => this.setState({ inputValue: '_ _ / _ _' })}
/>
</div>
);
}
}
export default App;
import React,{Component}来自'React';
导入“/App.css”;
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
输入值:“”
};
this.update=this.update.bind(this);
}
更新(e){
e、 预防默认值();
常量formatString=''.'/.'';
const newString=`${e.target.value}${formatString.slice(
e、 target.value.length
)}}`;
this.setState({[e.target.name]:newString});
}
render(){
返回(
this.setState({inputValue:'.'./.'.'})}
/>
);
}
}
导出默认应用程序;
每次在输入框中键入新字符时,都会调用onChange事件。因此,您只需要该字符串的最后一个字符。这是按照以下步骤进行的
const lastChar=e.target.value[e.target.value.length-1]代码>
现在,您需要在格式化字符串中的某个位置替换它。为了跟踪位置,我使用了count
state变量。更新count变量是一个非常简单的逻辑,特定于输入字符串(位置0,2,6,8需要按相同顺序替换)。最后,您将使用刚才提取的最后一个字符替换该特定位置
const newString=prevString.substr(0,count)+lastChar+prevString.substr(count+1)代码>
下面是一个工作示例 因此,每当用户键入某个内容时,它都会被替换为这个字符串“\uuuu/\uuuu/”对吗?是的,所以类似于0\uuu/\uuuu
,0 9/0
,0 9/0 9
,我会将其添加进去。太棒了,我只有一个问题,当用户单击框时,是否有方法将光标向前移动,并使光标随着每个数字的输入而移动?这仍然是一个很好的答案。我正在寻找这个。如果我发现了什么,我会让你知道并更新答案。