React父组件调用子组件属性和方法

子组件暴露自身的属性和方法
父组件使用ref绑定对应的子组件。调用即可

类组件绑定ref示例


import React from 'react'
import Child from './Child'

export default class Parent extends React.Component {
  // ...
  render() {
    return (
      <div>
        <Child ref={ref => this.refChild = ref} />
        {/* ... */}
      </div>
    )
  }
}

函数组件绑定ref示例

import React, { useRef } from 'react'
import Child from './Child'

export default function Parent(props) {
  const refChild = useRef(null)
  // ...
  return (
    <div>
      <Child ref={refChild} />
      {/* ... */}
    </div>
  )
}

子组件为类组件

当子类为类组件时,比较简单,无需特殊处理。

子类的实例可以直接调用类属性和方法。

这是ES6固有的语法

// 子组件为类组件时 - 示例代码

import React from 'react'

export default class Child extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 1,
      name: 'wmm66'
    }
  }
  addCount = (step) => {
    this.setState((state, props) => {
      return { count: state.count + step }
    })
  }
  render() {
    const { count, name } = this.state
    return (
      <div>
        <div>{count} -- {name}</div>
        <button onClick={this.addCount.bind(this, 2)}>加2</button>
      </div>
    )
  }
}

// 父组件调用子组件示例

console.log('child count: ', this.refChild.state.count)
this.refChild.addCount(3)

子组件为函数组件

当子类为函数组件时,需要使用React.forwardRef包裹。

并用React.useImperativeHandle将需要访问的属性和方法暴露出去

// 子组件为函数组件时 - 示例代码

import React, { useState, useImperativeHandle, forwardRef } from 'react'

const Child = forwardRef(function _Child(props, ref) {
  // 将外部需要访问的属性和方法暴露出去
  useImperativeHandle(ref, () => ({
    count,
    addCount,
  }))

  const [count, setCount] = useState(1)
  const [name, setName] = useState('wmm66')

  const addCount = (step) => {
    setCount(count + step)
  }

  return (
    <div>
      <div>{count} -- {name}</div>
      <button onClick={() => addCount(2)}>加2</button>
    </div>
  )
})

export default Child

父组件调用子组件示例

console.log('child count: ', refChild.current.count)
refChild.current.addCount(step)
posted @ 2023-04-04 14:50  风意不止  阅读(1963)  评论(0编辑  收藏  举报