为了摆脱繁琐的Dom操作, React提倡组件化, 组件内部用数据来驱动视图的方式,来实现各种复杂的业务逻辑 ,然而,当我们为原始Dom绑定事件的时候, 还需要通过组件获取原始的Dom, 而React也提供了ref为我们解决这个问题.
为什么不能从组件直接获取Dom?
组件并不是真实的 DOM 节点,而是存在于内存之中的一种数据结构,叫做虚拟 DOM (virtual DOM)。只有当它插入文档以后,才会变成真实的 DOM
如果需要从组件获取真实 DOM 的节点,就要用到官方提供的ref属性
使用场景
当用户加载页面后, 默认聚焦到input框
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
import React, { Component } from 'react' ;
import './App.css' ;
// React组件准确捕捉键盘事件的demo
class App extends Component {
constructor(props) {
super (props)
this .state = {
showTxt: ""
}
this .inputRef = React.createRef();
}
// 为input绑定事件
componentDidMount(){
this .inputRef.current.addEventListener( "keydown" , (event)=>{
this .setState({showTxt: event.key})
})
// 默认聚焦input输入框
this .inputRef.current.focus()
}
render() {
return (
<div className= "app" >
<input ref={ this .inputRef}/>
<p>当前输入的是: <span>{ this .state.showTxt}</span></p>
</div>
);
}
}
export default App;
|
自动聚焦input动画演示

使用场景
为了更好的展示用户输入的银行卡号, 需要每隔四个数字加一个空格
实现思路:
当用户输入的字符个数, 可以被5整除时, 额外加一个空格
当用户删除数字时,遇到空格, 要移除两个字符(一个空格, 一个数字),
为了实现以上想法, 必须获取键盘的BackSpace事件, 重写删除的逻辑
限制为数字, 隔四位加空格
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import React, { Component } from 'react' ;
import './App.css' ;
// React组件准确捕捉键盘事件的demo
class App extends Component {
constructor(props) {
super (props)
this .state = {
showTxt: ""
}
this .inputRef = React.createRef();
this .changeShowTxt = this .changeShowTxt.bind( this );
}
// 为input绑定事件
componentDidMount(){
this .inputRef.current.addEventListener( "keydown" , (event)=>{
this .changeShowTxt(event);
});
// 默认聚焦input输入框
this .inputRef.current.focus()
}
// 处理键盘事件
changeShowTxt(event){
// 当输入删除键时
if (event.key === "Backspace" ) {
// 如果以空格结尾, 删除两个字符
if ( this .state.showTxt.endsWith( " " )){
this .setState({showTxt: this .state.showTxt.substring(0, this .state.showTxt.length-2)})
// 正常删除一个字符
} else {
this .setState({showTxt: this .state.showTxt.substring(0, this .state.showTxt.length-1)})
}
}
// 当输入数字时
if ([ "0" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" ].includes(event.key)){
// 如果当前输入的字符个数取余为0, 则先添加一个空格
if (( this .state.showTxt.length+1)%5 === 0){
this .setState({showTxt: this .state.showTxt+ ' ' })
}
this .setState({showTxt: this .state.showTxt+event.key})
}
}
render() {
return (
<div className= "app" >
<p>银行卡号 隔四位加空格 demo</p>
<input ref={ this .inputRef} value={ this .state.showTxt}/>
</div>
);
}
}
export default App;
|

小结:
虚拟Dom虽然能够提升网页的性能, 但虚拟 DOM 是拿不到用户输入的。为了获取文本输入框的一些操作, 还是js原生的事件绑定机制最好用~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。