React 基础笔记(React使用Hooks-useRef)(二十六)

React_Hooks_Ref

在 Hooks 中想获取到节点

  • useRef

当获取到的节点在方法内 而不是子组件的时候

import React, { useState, useRef, useEffect } from 'react'
import SecondComponent from './Second'
function App() {
  const [count, setcount] = useState(0)
  const countRef = useRef()
  function handleClick() {
    setcount(() => {
      return count + 1
    })
  }
  useEffect(() => {
    console.log(countRef)
    console.log(countRef.current)
  })
  return (
    <div>
      <span>{count}</span>
      <button onClick={handleClick} ref={countRef}>
        点击
      </button>
      <SecondComponent count={count}></SecondComponent>
    </div>
  )
}
export default App

但是想要获取到子组件的 ref ,那子组件必须是类的形式 否则会报错误,获取不到值

  • 子组件
import React, { Component } from 'react'
class SecondComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      message: '子组件',
    }
  }
  render() {
    return (
      <div>
        {this.props.count} --{this.state.message}
      </div>
    )
  }
}

export default SecondComponent
  • 父组件
import React, { useState, useRef, useEffect } from 'react'
import SecondComponent from './Second'
function App() {
  const [count, setcount] = useState(0)
  const countRef = useRef()
  function handleClick() {
    setcount(() => {
      return count + 1
    })
  }
  useEffect(() => {
    console.log(countRef)
    console.log(countRef.current)
  })
  return (
    <div>
      <span>{count}</span>
      <button onClick={handleClick}>点击</button>
      <SecondComponent count={count} ref={countRef}></SecondComponent>
    </div>
  )
}
export default App

Ref 有的时候也可以用于保存上次状态的值

function useCounter() {
  const [count, setCoount] = useState(0)
  const [updater, setUpdater] = useState(0)
  const prevCountRef = useRef()
  useEffect(() => {
    prevCountRef.current = count
  })
  const prevCount = prevCountRef.current
  return (
    <h1>
      Now:{count},Before:{prevCount}
    </h1>
  )
}

文章作者: 雾烟云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 雾烟云 !
  目录