【问题标题】:How to access ref from a non-related component?如何从不相关的组件访问 ref?
【发布时间】:2020-03-29 07:36:47
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs react-forwardref


    【解决方案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>
      )
    }
    

    【讨论】:

    • 感谢您的回复。问题是这两个组件在应用程序架构中距离太远。走这条路会涉及大量的传球,我认为这不是一个干净的方式。
    • 那么你的问题不是参考,它只是道具钻孔。有两种主要的解决方案 - useContext() 和组合模式。
    猜你喜欢
    • 2020-02-24
    • 2022-01-08
    • 2018-01-03
    • 2018-11-18
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2018-10-09
    • 2019-09-18
    相关资源
    最近更新 更多