[React] The parent component calls the method of the child component

1 Implementation method of function components:

parent component:

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

const Parent = ()=>{
    
    

    const ChildRef = React.createRef();
    
    return (
        <div onClick={
    
    () => ChildRef.current.handleChild()}>
			<Child onRef={
    
    ChildRef}/>
        </div>
    )
}

Subassembly:

import React, {
    
     useImperativeHandle } from "react";

const Child = (props)=>{
    
    

	useImperativeHandle(props.onRef, () => {
    
    
    	return {
    
    
			handleChild: getList,
    	}
	})
    
    const getList = ()=>{
    
     console.log('子组件方法') }
    
    return <div>子组件</div>
}

2 types of component implementation:

parent component:

import React,{
    
    Component} from 'react';
import Child from './Child'

export default class Parent extends Component{
    
    
  componentDidMount () {
    
    
    this.child.test('父组件参数')
  }
  onRef = (ref)=> {
    
    
    this.child=ref//接收子组件this
  }
  render () {
    
    
    return (
      <div>
        <Child onRef={
    
     this.onRef}/>
      </div>
    )
  }
};

Subassembly:

import React,{
    
    Component} from 'react';

export default class Child extends Component{
    
    
  componentDidMount () {
    
    
    this.props.onRef(this)//传递子组件this
  }
  test = (val)=> {
    
    
    console.log(val)
  }
  render () {
    
    
    return <div>子组件</div>
  }
};

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/126489971