react父组件调用子组件的方法小结

9044次浏览

前言

本文是小结类文章,主要总结一下工作中遇到的父组件调用子组件方法。当然除了用ref之外还有很多其他方式,本文仅仅列举ref的方式。分别介绍父子组件都为class;父子组件都是hooks;父组件是class子组件是hooks;父组件是hooks,子组件是class的各种情况的调用方式。

父子组件都为class

父子组件都是class,父组件调用子组件方式比较传统,方法如下:

// 父组件
import React, {Component} from 'react';
export default class Parent extends Component {
    render() {
        return(
            <div>
                <Child onRef={this.onRef} />
                <button onClick={this.click} >click</button>
            </div>
        )
    }
    onRef = (ref) => {
        this.child = ref
    }
    click = (e) => {
        this.child.myName()
    }
}

//子组件
class Child extends Component {    
   componentDidMount(){        //必须在这里声明,所以 ref 回调可以引用它
        this.props.onRef(this)
    }
    myName = () => alert('my name is haorooms blogs')
    render() {
        return (<div>haorooms blog test</div>)
    }
}

父子组件都为hooks

一般我们会结合useRef,useImperativeHandle,forwardRef等hooks来使用,官方推荐useImperativeHandle,forwardRef配合使用,经过实践发现forwardRef不用其实也是可以的,只要子组件把暴露给父组件的方法都放到useImperativeHandle里面就可以了。

/* FComp 父组件 */
import {useRef} from 'react';
import ChildComp   from './child'
const FComp = () => {
    const childRef = useRef();
    const updateChildState = () => {
        // changeVal就是子组件暴露给父组件的方法
        childRef.current.changeVal(99);
    }
    return (
        <>
            <ChildComp ref={childRef} />
            <button onClick={updateChildState}>触发子组件方法</button>
        </>
    )
}

import React, { useImperativeHandle, forwardRef } from "react"
let Child = (props, ref) => {
 const [val, setVal] = useState();
  useImperativeHandle(ref, () => ({ // 暴露给父组件的方法
     getInfo,
      changeVal: (newVal) => {
          setVal(newVal);
        },
      refreshInfo: () => {
        console.log("子组件refreshInfo方法")
    }
  }))

  const getInfo = () => {
    console.log("子组件getInfo方法")
  }

  return (
    <div>子组件</div>
  )
}
Child = forwardRef(Child)
export default Child

父组件为class,子组件为hooks

其实就是上面的结合体。子组件还是用useImperativeHandle ,可以结合forwardRef,也可以不用。

// 父组件class
class Parent extends Component{
  child= {} //主要加这个
  handlePage = (num) => {
    // this.child.
    console.log(this.child.onChild())
  }
   onRef = ref => {
    this.child = ref
  }
render() {
   return {
     <ListForm onRef={this.onRef} />
   }
 }
}

// 子组件hooks
import React, { useImperativeHandle } from 'react'
const ListForm = props => {
  const [form] = Form.useForm()

  //重置方法
  const onReset = () => {
    form.resetFields()
  }
}

 useImperativeHandle(props.onRef, () => ({
    // onChild 就是暴露给父组件的方法
    onChild: () => {
      return form.getFieldsValue()
    }
  }))
  ..............

父组件为hooks,子组件是class

这里其实和上面差不多,react主要dom省略,仅展示精华部分

//父组件hooks
 let richTextRef = {};
// richTextRef.reseditorState();调用子组件方法
  <RichText 
      getRichText={getRichText} 
      content={content} 
      onRef={ref => richTextRef = ref} 
  />

//子组件class
  componentDidMount = () => {
    this.props.onRef && this.props.onRef(this);// 关键部分
  }

   reseditorState = (content) => {
    this.setState({
      editorState: content ||'-',
    })
  }

小结

本文主要是总结,有些朋友在hooks或者class混合使用的时候,不清楚怎么调用子组件方法,这里总结一下,希望对各位小伙伴有所帮助。

相关文章: