Reactjs 如何从非相关组件访问ref?

Reactjs 如何从非相关组件访问ref?,reactjs,react-forwardref,Reactjs,React Forwardref,我有一个固定定位的导航栏,当应用程序中的某些菜单展开时,我想使其保持静态。 问题在于,在应用程序hirarchy中,这两个组件彼此都相距很远 const Nav=()=>{ const navRef=useRef(空); 返回( ); } 常量菜单=()=>{ //我想在这里访问导航参考,以便在菜单展开时更改其样式 返回( ) }您可以这样做 const App = () => { const navRef = useRef(); const setStyleForNav =

我有一个固定定位的导航栏,当应用程序中的某些菜单展开时,我想使其保持静态。
问题在于,在应用程序hirarchy中,这两个组件彼此都相距很远

const Nav=()=>{
const navRef=useRef(空);
返回(
);
}
常量菜单=()=>{
//我想在这里访问导航参考,以便在菜单展开时更改其样式
返回(
    )
    }
    您可以这样做

    const App = () => {
      const navRef = useRef();
    
      const setStyleForNav = (style) => {
        navRef.current.style = style;  
      };
    
      return (
        <Nav ref={navRef}/>
        <Menu setStyleForNav={setStyleForNav}/>
      )
    };
    
    const Nav = React.forwardRef((props, ref) => {
      return (
        <nav
          ref={ref}
        ></nav>
      );
    });
    
    const Menu = ({setStyleForNav}) => {
      // I want to access the nav ref here to change its style when the menu expands
      return (
        <ul></ul>
      )
    }
    
    const-App=()=>{
    const navRef=useRef();
    const setStyleForNav=(样式)=>{
    navRef.current.style=样式;
    };
    返回(
    )
    };
    const Nav=React.forwardRef((道具,ref)=>{
    返回(
    );
    });
    常量菜单=({setStyleForNav})=>{
    //我想在这里访问导航参考,以便在菜单展开时更改其样式
    返回(
    
      ) }
      感谢您的回复。问题是这两个组件在应用程序架构中距离太远。走这条路需要大量的传球,我认为这不是一条干净的路。那么你的问题不是裁判,而是支柱训练。这个问题有两个主要解决方案-useContext()和组合模式。