react-10-refs

65 阅读1分钟

react-refs

一、refs 是什么?

refs 是一个获取dom节点或者获取react实例的工具。

二、类组件使用refs

// 子组件
import React, { Component } from "react"

export default class Input extends Component {
  render() {
    return <input type="text" />
  }
}
// 父组件
import React, { Component } from "react"
import Input from "./components/Input"

export default class App extends Component {
  // 第一种写法
  // myRef = React.createRef()
  // myRefDom = React.createRef()

  // 第二种写法
  constructor() {
    super()
    this.myRef = React.createRef()
    this.myRefDom = React.createRef()
  }
  render() {
    return (
      <div>
        App
        <hr />
        <Input ref={this.myRef} />
        <div ref={this.myRefDom}>dom元素</div>
      </div>
    )
  }
  componentDidMount() {
    console.log(this.myRef)
    console.log(this.myRefDom)
    console.log(this.myRefDom.current.innerHTML)
  }
}

三、类组件获取子组件的dom元素

利用子传父

父组件
import React, { Component } from "react"
import Child from "../components/Child"
export default class PageF extends Component {
  element = null
  render() {
    return (
      <div>
        PageF
        <hr />
        <Child
          callBack={(el) => {
            this.element = el
          }}
        />
      </div>
    )
  }
  componentDidMount() {
    console.log(this.element)
  }
}
子组件
import React, { Component } from "react"

export default class Child extends Component {
  childRef = React.createRef()
  render() {
    return (
      <div>
        <input type="text" ref={this.childRef} />
      </div>
    )
  }
  componentDidMount() {
    this.props.callBack(this.childRef.current)
  }
}

四、函数组件使用refs

forwardRef() 该方法用来转发ref,将父组件的ref转发给子组件的内的dom元素,该方法的返回值是一个组件。 该方法接收一个函数,这个函数就是render函数。 这个render函数接收两个参数,第一个参数是父组件传递过来的props,第二个参数是父组件传递过来的ref。

import React, { useRef, forwardRef, useImperativeHandle } from "react"

const Input = forwardRef((props, ref) => {
  const inputRef = useRef()
  const divRef = useRef()

  // 该方法用来决定暴露那些东西给父组件
  useImperativeHandle(ref, () => ({
    inputFoucus: () => {
      inputRef.current.focus()
    },
    // value999: inputRef.current.value   // 这样写 会一直获取到空字符串
    value999: () => inputRef.current.value,
    divEle: () => divRef.current
  }))

  return (
    <>
      <input ref={inputRef} type="text" />
      <hr />
      <div ref={divRef}>div</div>
    </>
  )
})

export default Input

import React, { useRef } from "react"
import Input from "./components/Input"

const App = () => {
  const myRef = useRef()

  return (
    <div>
      App
      <hr />
      <button
        onClick={() => {
          myRef.current.inputFoucus()
          console.log(myRef.current.value999())
          console.log(myRef.current.divEle())
        }}
      >
        获取焦点
      </button>
      <hr />
      <Input ref={myRef} />
    </div>
  )
}

export default App