useRef
1. 说明
useRef
返回一个可变的 ref 对象,返回的 ref 对象在组件的整个生命周期内保持不变。- 用途 :
2. 语法
2.1 语法格式
const myRef = useRef()
2.2 语法说明
import { useRef } from 'react'
const myRef = useRef()
myRef.current
3. 使用
3.1 用途1- 保持可变变量
const myRef = useRef(10)
<button onClick={ () => console.log('ref值', myRef.current ++ ) }></button>
3.2 用途2- 绑定DOM节点
const iptRef = useRef()
<input ref={iptRef} type="text" />
console.log('iptRef', iptRef.current.value)
3.3 useRef 用在定时器上
let timer; # 报警告 => 使用 useRef
useEffect(() => {
timer = setInterval(() => {
console.log('定时器')
}, 1000)
return () => {
console.log('卸载')
clearInterval(timer)
}
}, [])
- 使用 useRef 用在定时器timerId 保存变量
const timerRef = useRef()
useEffect(() => {
timerRef.current = setInterval(() => {
console.log('定时器')
}, 1000)
return () => {
console.log('卸载')
clearInterval(timerRef.current)
}
}, [])
4. Demo - 动画案例
const Child = () => {
const clickHandler = () => {}
return (
<div className="ref_container" onClick={clickHandler}>
<div className="ref_el"></div>
</div>
)
}
.ref_container {
height: 660px;
width: 375px;
background: pink;
border-top: 1px solid pink;
}
.ref_container .ref_el {
background: red;
width: 50px;
height: 50px;
margin-top: 100px;
}
const element = useRef();
<div className="ref_el" ref={element} />
import anime from 'animejs';
function ml_animate01() {
if (element) {
anime({
targets: element.current,
translateX: 300,
backgroundColor: '#ff8822',
borderRadius: ['0%', '50%'],
complete: () => {}
})
}
}
const clickHandler = () => {
ml_animate01()
}
function ml_animate01() {
complete: () => {
ml_animate02()
}
}
function ml_animate02() {
if (element) {
anime({
targets: element.current,
translateX: 0,
backgroundColor: '#f00',
borderRadius: ['50%', '0%'],
complete: () => {}
})
}
}
- 配合 useStat 和 useEffect 切换动画
const [isAnimate1, setAnimate1] = useState(false)
const [isAnimate2, setAnimate2] = useState(false)
useEffect(() => {
isAnimate1 && ml_animate01()
}, [isAnimate1])
useEffect(() => {
isAnimate2 && ml_animate02()
}, [isAnimate2])
function ml_animate01() {
...
complete: () => {
setAnimate1(false)
setAnimate2(true)
}
}
function ml_animate02() {
...
complete: () => {
setAnimate2(false)
}
}
const clickHandler = () => {
setAnimate1(true)
}