当使用onPaste event粘贴到Reactjs中的textfield中时,如何从字符串中移除空间,使出现在文本字段中的最终字符串之间没有空格。
我的HTML代码如下:
<input placeholder="Enter your First Name" onPaste={(event) => this.onFirstNamePaste(event)}/> 事件处理程序:
onFirstNamePaste(event){
var text = event.clipboardData.getData('Text')
this.value = text.replace(/\s/g,'');
}发布于 2017-07-31 16:51:31
试试这个:
onFirstNamePaste(event){
var text = event.clipboardData.getData('Text')
this.value = text.split(' ').join('');
}发布于 2017-07-31 17:09:09
对输入元素使用ref属性,
<input
ref={(nameInput) => { this.nameInput = nameInput; }}
placeholder="Enter your First Name"
onPaste={(event) => this.onFirstNamePaste(event)}
/>然后在函数内部,
onFirstNamePaste(event){
const text = event.clipboardData.getData('Text')
this.nameInput.value = text.split(' ').join('');
}还可以使用组件状态跟踪输入中的更改,并更新状态以反映更改。
<input
value={this.state.nameValue}
onChange={(e) => this.setState({ nameValue: e.target.value }) }
placeholder="Enter your First Name"
onPaste={(event) => this.onFirstNamePaste(event)}
/>在粘贴功能中,
onFirstNamePaste(event){
const text = event.clipboardData.getData('Text')
const value = text.split(' ').join('');
this.setState({ nameValue: value });
}https://stackoverflow.com/questions/45421344
复制相似问题