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

青灯夜游
Release: 2022-12-27 19:01:42
Original
18850 people have browsed it

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 
子组件
; } } class Super extends Component { constructor(props) { super(props); this.sub = React.createRef(); } handleOnClick() { this.sub.callback(); } render() { return (
); } }
Copy after login

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.

...  this.sub = ref}> ...
Copy after login

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 'react'; import { observer } from 'mobx-react' @observer class Sub extends Component { componentDidMount(){ // 将子组件指向父组件的变量 this.props.onRef && this.props.onRef(this); } callback(){ console.log("执行我") } render(){ return (
子组件
); } } class Super extends Component { handleOnClick(){ // 可以调用子组件方法 this.Sub.callback(); } render(){ return (
click
this.Sub = node }>
) } }
Copy after login

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 'react'; import { observer } from 'mobx-react' const Parent = () => { let ChildRef = React.createRef(); function handleOnClick() { ChildRef.current.func(); } return ( 
); }; const Child = observer(props => { //用useImperativeHandle暴露一些外部ref能访问的属性 useImperativeHandle(props.onRef, () => { // 需要将暴露的接口返回出去 return { func: func, }; }); function func() { console.log('执行我'); } return
子组件
; }); export default Parent;
Copy after login

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 'react'; import ReactDOM from 'react-dom'; import { observer } from 'mobx-react' const FancyInput = React.forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return  }); const Sub = observer(FancyInput) const App = props => { const fancyInputRef = useRef(); return ( 
) } export default App;
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!