0

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

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>
  )
}

4

1 回答 1

1

你可以做这样的事情......

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>
  )
}
于 2020-03-29T08:13:37.633 回答