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 に答える