如何从非相关组件访问ref



我有一个固定位置的导航栏,当应用程序中的一些菜单展开时,我想使其成为静态的
问题是,在应用程序层次结构中,两个组件相距甚远。

const Nav = () => {
const navRef = useRef(null);
return (
<nav
ref={navRef}
></nav>
);
}
const Menu = () => {
// 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 = (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>
)
}

最新更新