在使用 React 函数组件时,我们可以使用 useImperativeHandle hook,来暴露一些方法或属性给父组件调用。但是在 Class 组件中,我们需要使用 React.forwardRefReact.createRef 来实现类似的功能。

具体实现步骤如下:

  1. 在子组件中定义需要暴露给父组件的方法或属性,并使用 useImperativeHandle hook 来实现:
import React, { forwardRef, useImperativeHandle, useState } from 'react'

const Child = forwardRef((props, ref) => {
  const [count, setCount] = useState(0)

  useImperativeHandle(ref, () => ({
    increment() {
      setCount(count + 1)
    },
    getCount() {
      return count
    }
  }))

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  )
})

export default Child
  1. 在父组件中使用 React.createRef 来创建一个 ref,然后将该 ref 传递给子组件:
import React, { Component } from 'react'
import Child from './Child'

class Parent extends Component {
  constructor(props) {
    super(props)
    this.childRef = React.createRef()
  }

  handleClick = () => {
    this.childRef.current.increment()
  }

  render() {
    return (
      <div>
        <Child ref={this.childRef} />
        <button onClick={this.handleClick}>Increment</button>
      </div>
    )
  }
}

export default Parent

在父组件中,我们可以通过 this.childRef.current 来获取子组件中暴露的方法或属性。例如,我们可以通过 this.childRef.current.increment() 来调用子组件中的 increment 方法,从而实现点击按钮增加计数器的功能。

react中useImperativeHandle,对应在class组件的使用方式

原文地址: http://www.cveoy.top/t/topic/uhq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录