react项目,如何使用ref指代一个变量?非常规dom引用
发布于 作者:苏南大叔 来源:程序如此灵动~
在react项目中,可以使用ref来指代某一个dom对象,然后再通过.current获得引用。一般情况下,是使用ref来指定某个输入框的,但是在本文的例子中,引用对象是个摸不到看不着的计时器对象。那么,ref如何和非dom对象结合使用呢?

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文描述:在react项目中,ref和计时器Interval的配合使用问题。测试环境:create-react-app@5.0.1,react@18.2.0,react-dom@18.2.0,node@16.14.2。
本文使用了两种写法来实现如下效果:一个数字从0走到6,一秒变一个数。使用ref而不使用普通变量的原因,是因为更新state就会触发重新渲染,重新渲染就会重置变量,那么就会导致前功尽弃,而使用ref.current就可以规避这个问题。
类式组件
react项目中,ref有两种创建方式。第一种是应用于类组件的createRef:
本文代码能正常执行的前提是:禁用StrictMode。参考文章:
本节内容看看,如何不指代具体的组件,而是一个变量。代码如下:
import React, { Component } from 'react'
export default class Child extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.timerRef = React.createRef(null);
}
render() {
console.log(this.timerRef.current);
if (!this.timerRef.current) {
this.timerRef.current = window.setInterval(() => {
this.setState((state) => {
return { count: state.count + 1 }
});
}, 1000);
}
if (this.state.count > 5) {
console.log("clear");
window.clearInterval(this.timerRef.current);
}
return (
<div>
{this.state.count}
</div>
)
}
}
函数式组件
react项目中,ref有两种创建方式。第二种是应用于函数组件的useRef:
本文代码能正常执行的前提是:禁用StrictMode。参考文章:
本节内容看看,如何不指代具体的组件,而是一个变量。代码如下:
import React, { useState, useRef } from 'react';
export default function Child(props) {
const timerRef = useRef(null);
const [count, setCount] = useState(0);
console.log(timerRef.current);
if (!timerRef.current) {
timerRef.current = window.setInterval(() => {
setCount(count => count + 1);
}, 1000);
}
if (count > 5) {
console.log("clear");
window.clearInterval(timerRef.current);
}
return (
<>
{count}
</>
);
}
特殊说明.current
事项一: 无论是createRef()还是useRef(),都可以设置初始的.current默认值【画黑板重点!】。本文中,正是通过默认值NULL来区分是否被初始化的。
事项二: 手工通过代码对ref赋值的话,是ref.current = ;,而不是ref = ;。
if (!ref.current) {
ref.current = ;
}事项三: 再次声明,本文需要禁用StrictMode,否则会得到多个计时器变量,无法清除停止计时器。
相关文章
- https://newsn.net/say/react-useref.html
- https://newsn.net/say/react-createref.html
- https://newsn.net/say/create-react-app.html
总结
更多苏南大叔的react经验文章,请点击: