我们相信:世界是美好的,你是我也是。平行空间的世界里面, 不同版本的生活 也在继续...

react 项目中,可以使用 ref 来指代某一个 dom 对象,然后再通过 .current 获得引用。一般情况下,是使用 ref 来指定某个输入框的,但是在本文的例子中,引用对象是个摸不到看不着的计时器对象。那么, ref 如何和非 dom 对象结合使用呢?

苏南大叔:react项目,如何使用ref指代一个变量?非常规dom引用 - react-ref-not-dom
react项目,如何使用ref指代一个变量?非常规dom引用(图3-1)

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文描述:在 react 项目中, ref 和计时器 Interval 的配合使用问题。测试环境: [email protected] [email protected] [email protected] [email protected]

本文使用了两种写法来实现如下效果:一个数字从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 (
        {this.state.count}
}

苏南大叔:react项目,如何使用ref指代一个变量?非常规dom引用 - ref-code-1
react项目,如何使用ref指代一个变量?非常规dom引用(图3-2)

函数式组件

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 (