You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.0 KiB

2 years ago
  1. import React, { useEffect, useRef } from 'react'
  2. // useRef:在函数组件中获取真实的dom元素对象或者是组件对象
  3. /**
  4. * 使用步骤
  5. * 1. 导入 useRef 函数
  6. * 2. 执行 useRef 函数并传入null返回值为一个对象 内部有一个current属性存放拿到的dom对象类组件实例
  7. * 3. 通过ref 绑定 要获取的元素或者组件
  8. */
  9. class TestC extends React.Component {
  10. state = {
  11. name: 'Ken'
  12. }
  13. getName = () => {
  14. return 'this is child Test'
  15. }
  16. render () {
  17. return (
  18. <div>类组件</div>
  19. )
  20. }
  21. }
  22. function App () {
  23. const testRef = useRef(null)
  24. const h1Ref = useRef(null)
  25. // useEffect 回调是在 dom 渲染之后的。和 vue 里的 watch 效果较像,但是执行时机是不同的
  26. useEffect(() => {
  27. console.log(testRef.current)
  28. console.log(h1Ref.current)
  29. }, [])
  30. return (
  31. <div>
  32. <TestC ref={testRef}/>
  33. <h1 ref={h1Ref}>this is h1</h1>
  34. </div>
  35. )
  36. }
  37. export default App