Home  >  Article  >  Web Front-end  >  How to call the method of child component in React parent component

How to call the method of child component in React parent component

青灯夜游
青灯夜游Original
2022-12-27 19:01:4218958browse

Calling method: 1. Calls in class components can be implemented using React.createRef(), functional declaration of ref or props custom onRef attribute; 2. Calls in function components and Hook components can be implemented using UseImperativeHandle or forwardRef throws child component ref to achieve this.

How to call the method of child component in React parent component

#The operating environment of this tutorial: Windows7 system, react18 version, Dell G3 computer.

In React, we often call the method of the parent component in the child component, usually using props callback. But sometimes it is also necessary to call the child component's method in the parent component to achieve high cohesion. There are many methods, take them as needed.

In class components


1, React.createRef()

  • Advantages: easy to understand, pointed by ref.

  • Disadvantages: Subcomponents using HOC are not available and cannot point to real subcomponents

    For example, some commonly used writing methods, subcomponents wrapped by mobx's @observer are not This method applies.

import React, { Component } from 'react';

class Sub extends Component {
  callback() {
    console.log('执行回调');
  }
  render() {
    return <div>子组件</div>;
  }
}

class Super extends Component {
  constructor(props) {
    super(props);
    this.sub = React.createRef();
  }
  handleOnClick() {
    this.sub.callback();
  }
  render() {
    return (
      <div>
        <Sub ref={this.sub}></Sub>
      </div>
    );
  }
}

2. Functional declaration of ref

  • Advantages: ref writing is simple
  • Disadvantages: Used HOC subcomponents are not available and cannot point to real subcomponents (same as above)

The usage method is the same as above, but the way of defining ref is different.

...

<Sub ref={ref => this.sub = ref}></Sub>

...

3. Use props to customize the onRef attribute

  • Advantages: If the subcomponent is nested with HOC, it can also point to the real subcomponent.
  • Disadvantages: Need to customize props attributes
import React, { Component } from &#39;react&#39;;
import { observer } from &#39;mobx-react&#39;

@observer
class Sub extends Component {
	componentDidMount(){
    // 将子组件指向父组件的变量
		this.props.onRef && this.props.onRef(this);
	}
	callback(){
		console.log("执行我")
	}
	render(){
		return (<div>子组件</div>);
	}
}

class Super extends Component {
	handleOnClick(){
       // 可以调用子组件方法
		this.Sub.callback();
	}
	render(){
		return (
          <div>
			<div onClick={this.handleOnClick}>click</div>
			<Sub onRef={ node => this.Sub = node }></Sub>	
	   	  </div>)
	}
}

Function component, Hook component


1, useImperativeHandle

  • advantage: 1. The writing method is simple and easy to understand. 2. If the subcomponent has a nested HOC, it can also point to the real subcomponent
  • Disadvantages: 1. Need to customize props attributes 2. Need to customize the exposed method
import React, { useImperativeHandle } from &#39;react&#39;;
import { observer } from &#39;mobx-react&#39;


const Parent = () => {
  let ChildRef = React.createRef();

  function handleOnClick() {
    ChildRef.current.func();
  }

  return (
    <div>
      <button onClick={handleOnClick}>click</button>
      <Child onRef={ChildRef} />
    </div>
  );
};

const Child = observer(props => {
  //用useImperativeHandle暴露一些外部ref能访问的属性
  useImperativeHandle(props.onRef, () => {
    // 需要将暴露的接口返回出去
    return {
      func: func,
    };
  });
  function func() {
    console.log(&#39;执行我&#39;);
  }
  return <div>子组件</div>;
});

export default Parent;

2. forwardRef

Use forwardRef to throw the ref of the subcomponent

This method is actually More suitable for custom HOC. But the problem is that withRouter, connect, Form.create and other methods cannot throw ref. If Child itself needs to nest these methods, then they basically cannot be used together. forwardRef itself is also used to throw refs of child elements, such as input and other native elements. It is not suitable for throwing component refs because the usage scenarios of components are too complex.

import React, { useRef, useImperativeHandle } from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;
import { observer } from &#39;mobx-react&#39;

const FancyInput = React.forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} type="text" />
});

const Sub = observer(FancyInput)

const App = props => {
  const fancyInputRef = useRef();

  return (
    <div>
      <FancyInput ref={fancyInputRef} />
      <button
        onClick={() => fancyInputRef.current.focus()}
      >父组件调用子组件的 focus</button>
    </div>
  )
}

export default App;

Summary

There are two situations when a parent component calls a sub-component function

  • The sub-component has no HOC nesting: it is recommended to use ref to call it directly
  • There is HOC nesting: it is recommended to use custom props

[Related recommendations:Redis video tutorial, Programming teaching

The above is the detailed content of How to call the method of child component in React parent component. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn