一、什么是refs?
React提供的这个ref属性,表示为对组件真正实例的引用,其实就是ReactDOM.render() 返回的组件实例,
ref
可以挂到任何组件上,可以挂到组件上,也可以是dom元素上:
- 挂到组件(有状态组件)上时,
ref
返回的是组件实例的引用
; - 挂载到dom元素时,
ref
返回是具体的dom节点
二、refs 的使用
1、string ref 的使用 (React out API)
class Demo extends React.Component{
alertMsg=()=>{
console.log(this.refs)
const {
input1} = this.refs
alert(input1.value)
}
loseFocus=()=>{
const {
input2} = this.refs
alert(input2.value)
}
render (){
return (
<div>
<input ref="input1"></input>
<button onClick={
this.alertMsg}>点击我弹出左侧内容</button>
<input ref="input2" onBlur={
this.loseFocus}></input>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
2、回调 ref 的使用 (Before React V16)
class Demo extends React.Component{
alertMsg=()=>{
console.log(this)
const {
input1} = this
alert(input1.value)
}
loseFocus=()=>{
const {
input2} = this
alert(input2.value)
}
setCallBackRef = c =>{
// console.log(c) //这里的 c 是 input type="password" DOM元素
this.input2 = c
}
render (){
return (
<div>
<input type="text" ref={
c => this.input1 = c}></input>
<button onClick={
this.alertMsg}>点击我弹出左侧内容</button>
<input type="password" ref={
this.setCallBackRef} onBlur={
this.loseFocus}></input>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
- 页面初始化:
如果是第一次加载组件,第一次执行 render 函数,传入 Dom 元素
- 更新组件:(setState等操作)
如果 ref 回调函数是以内联函数(
c => this.input1 = c
)的方式(callback ref
)定义的,在更新过程中它会被执行两次,
第一次传入参数 null (重新执行 render 函数,此时创建了一个新的匿名函数,之前的
c => this.input1 = c
已经被释放了 传入了null
),在第二次才会传入参数 DOM 元素
。
这是因为在每次渲染时会创建一个新的函数实例,更新时也是会重新执行render函数,所以 React 清空旧的 ref 并且设置新的。
通过将 ref 的回调函数定义成 class 的绑定函数的方式(也就是上面的
this.setCallBackRef
)
可以避免上述问题,但是大多数情况下它是无关紧要的。
3、createRef 的使用 (After React V16)
class Demo extends React.Component{
// React.createRef()调用后,返回一个可以存储被ref所标识的节点,不能重复使用,会覆盖
inputRef1 = React.createRef()
inputRef2 = React.createRef()
alertMsg=()=>{
console.log(this.inputRef1) //输出 {
current: input }
alert(this.inputRef1.current.value)
}
loseFocus=()=>{
console.log(this.inputRef2) //输出 {
current: input }
alert(this.inputRef2.current.value)
}
render (){
return (
<div>
<input ref={
this.inputRef1}></input>
<button onClick={
this.alertMsg}>点击我弹出左侧内容</button>
<input ref={
this.inputRef2} onBlur={
this.loseFocus}></input>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
三、refs 的总结
推荐第三种方法 createRef
来使用ref
四、事件处理
- 通过
onXxx
属性指定事件处理函数(注意大小写)- React使用的是自定义(合成)事件,而不是使用的原生DOM事件 (兼容性)
- React中的事件是通过
事件委托方式
处理的(委托给组件最外层的元素
) (高效性)
- 通过
event.target
得到发生事件的DOM元素对象 (不用过度使用ref
)
转载:https://blog.csdn.net/iChangebaobao/article/details/117256624
查看评论