欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

react Hooks :useRef的使用

程序员文章站 2022-05-29 11:57:37
...
//useRef 作用 获取子组件或者DOM节点的句柄,渲染周期之间共享数据的存储

import React, { useState, useEffect, PureComponent, useMemo, useRef, useCallback } from 'react'

//函数组件获取不了ref

class Counter extends PureComponent {

  speak = () => {
    console.log('speak', this.props.count)
  }

  render() {
    const { props } = this
    return (
      <h1 onClick={props.onClick}>{props.count}</h1>
    )
  }
}


function APP(props) {

  const [count, setCount] = useState(0)

  const double = useMemo(() => {
    return count * 2
  }, [count === 3])

  const CounterRef = useRef()//使用CounterRef获取Counter这个组件

  const onClick = useCallback(() => {
    console.log('Click')//
    // console.log(CounterRef.current)//CounterRef.current返回就是Counter这个组件
    CounterRef.current.speak()//通过Counter组件的speak()
  }, [CounterRef])

  const it = useRef()

  useEffect(() => {
    it.current = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
    //定时器,让count每秒加1
  }, [])

  useEffect(() => {
    if (count >= 10) {
      clearInterval(it.current)
      //清除定时器
    }
  })
  return (
    <div>
      <button
        type="button"
        onClick={() => { setCount(count + 1) }}
      >
        Click({count}),double:{double}
      </button>
      <Counter ref={CounterRef} count={count} onClick={onClick} />
    </div>
  )
}

export default APP

相关标签: react.js react