react ref場景的使用場景及使用方式
ref主要用來做什么的
- 用來直接操作DOM,來完成一些操作
- 焦點,選中,動畫等
兩個常見的使用場景
- 獲取元素的寬度來完成某些動畫
- 獲取/失去輸入框焦點
幾種創建方式
this.ref1 = ref => {this.refDom = ref}
this.ref2 = React.createRef()
React.forwardRef
- 用來操作子組件中的ref對象,ref作為forwardRef函數的第二個參數返回
import React, { Component } from 'react'
const Child = React.forwardRef((props, ref) => {
return (
<input type='text' ref={ref} />
)
})
class Ref extends Component {
constructor (props) {
super(props)
this.ref3 = React.createRef()
}
handleFocus = () => {
console.log(this.ref4)
this.ref3.current.focus()
}
render() {
return (
<div>
<Child ref={this.ref3} />
<button onClick={() => this.handleFocus()}>獲得焦點</button>
</div>
)
}
}
export default Ref
class組件中ref的使用
- 在react16.3之前,ref的綁定方式
<span ref={ref => this.ref2 = ref} onClick={() => this.handleClick1()}>ref class v16.3前版本</span>
- 在react16.3之后,
<div ref={this.ref1} onClick={() => this.handleClick()}>ref class v16.3后版本</div>
,this.ref1 = ref => {this.refDom = ref}
import React, { Component } from 'react'
const Child = React.forwardRef((props, ref) => {
return (
<input type='text' ref={ref} />
)
})
class Ref extends Component {
constructor (props) {
super(props)
this.ref1 = ref => {this.refDom = ref}
this.ref2 = React.createRef()
}
handleClick = () => {
const { offsetWidth } = this.refDom
console.log('width', offsetWidth)
}
handleClick1 = () => {
const { offsetWidth } = this.ref2
console.log('width1', offsetWidth)
}
render() {
return (
<div>
<div ref={this.ref1} onClick={() => this.handleClick()}>ref class v16.3后版本</div>
<span ref={ref => this.ref2 = ref} onClick={() => this.handleClick1()}>ref class v16.3前版本</span>
</div>
)
}
}
export default Ref
react hooks中使用ref
import React, { useEffect, useRef } from 'react'
function ChildInput(props, ref) {
return (
<input type="text" ref={ref} />
)
}
const Child = React.forwardRef(ChildInput)
function RefHooks() {
const ref1 = useRef(null)
const ref2 = useRef(null)
useEffect(() => {
const width = ref1.current ? ref1.current.offsetWidth : 0
console.log('width', width, ref1.current)
}, [ref1.current])
const handleFocus = () => {
ref2.current.focus()
}
return (
<div>
<div ref={ref1}>ref hooks</div>
<Child ref={ref2} />
<button onClick={handleFocus}>獲得焦點</button>
</div>
)
}
export default RefHooks
react hooks typescript中使用ref
- useRef的使用
const ref = useRef<any>(null)
import React, { useEffect, useRef } from 'react'
function RefTs () {
const ref = useRef<any>(null)
useEffect(() => {
const width = ref.current ? ref.current.offsetWidth : 0
console.log('width', width)
}, [ref.current])
return (
<div>
<span ref={ref}>ref typescript</span>
</div>
)
}
export default RefTs
github查看更多好文:https://github.com/xccjk/x-blog