A, thinking
Understand how ref works, and then emulate ref, passing callRef to child components, which then pass methods to parent components via callRef.
Two, code implementation
Need to achieve the function: header call menu, in addition to menu itself can control the switch of menu, header also control the switch of menu
1. Sub-component Menu
import React, { useEffect, useState } from 'react'; export default function Menu(){ const { callRef } = props; Const callRef [isShow, setIsShow] = useState(false); //isShow: controls whether to expand the variable, setIsShow: UseEffect (() => {useEffect() => {if (callRef) {callRef(setIsShow); } }, [callRef]); Return (<div styleName={' menu-root ${isShow? 'isOpen' : ''}`} > ... . </div> ) }Copy the code
2. Parent component header call
import React, { useEffect, useState } from 'react'; import Menu from '.. /Menu'; Export default function Header(){let handleChangeMenuStatus = () => {}; Return (<div styleName="header-root"> < I className="kolicon kol-icon-menu1" onClick={() => handleChangeMenuStatus(true)}></i> {/* 3. */} <Menu callRef={(c) => {handleChangeMenuStatus = c; handleChangeMenuStatus = c; handleChangeMenuStatus = c; }}/> {/* 2. Assign the method returned by the child component to the variable */} </div>)}Copy the code
Third, summary
In conclusion, like ref, child components can pass methods directly to parent components, which can be easily used. In addition, if the React component is not a function, but a class component can do the same, and you can pass this of the child component to the parent component, the parent component can call more methods of the child component through this.