【问题标题】:React pass ref throw functional components in different levelsReact pass ref throw 不同级别的功能组件
【发布时间】:2020-08-11 07:26:05
【问题描述】:

我想滚动到页面中的菜单元素。

我的菜单组件不是我想滚动到的组件的父级。

我发现this post 描述了类似的问题

将 ref 传递给子元素 我们希望将 ref 附加到 dom 元素,而不是 React 组件。所以当把它传给孩子时

我们不能命名prop ref的组件。

    const myRef = useRef(null)
    return <ChildComp refProp={myRef}></ChildComp> }  ```

Then attach the ref prop to a dom element. ```jsx const ChildComp =
(props) => {
    return <div ref={props.refProp} /> } ```

这是我的应用结构

菜单组件:

const MenuApp = () => {
    return (
        <div>
            <div className="desktop-menu">
                <div className="menu-item a-propos">
                    <p className='button'>Me découvrir</p>
                </div>
                <div className="menu-item competences">
                    <p className='button'>Compétences </p>
                </div>
                <div className="menu-item experiences">
                    <p className='button'>Experiences</p>
                </div>
                <div className="menu-item formation">
                    <p className='button'>Formation </p>
                </div>
            </div>
        </div>
    )
}

父级是应用组件

 <div className="App">
  <div className="hero">
    <HeaderApp />
    <ApprochApp />
  </div>
  <Apropos />
  <Competences />
  <Experiences />
  <Formation />
  <Recom />
  <Contact />
  <Footer />
 </div >

我希望 mu 菜单滚动到主 App 组件中的反应组件

那么如何将菜单组件的引用传递给应用程序并在组件中使用它来滚动?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

虽然我不完全理解你的问题。但是,我从您的问题中可以看出一件事是您没有正确转发ref

在这种情况下你需要的是forwardRef

基本上,您需要做的是像这样创建childComponent

const childComponent = React.forwardRef(({...otherProps}, ref) => {
  return (<><div ref={ref}>Component content </div></>)
})

你需要在哪里使用组件你需要做的就是:

const parentComponent = () => {
  const reveiwsRef = React.useRef("");
  return (
   <div> 
      <childComponent ref={reviewsRef} />
   </div>
  );
}

您可以在 react 文档中找到更多信息:Forwarding-Refs

我希望这会有所帮助

【讨论】:

  • 我想做的是在单击菜单元素时滚动抛出一个页面。菜单组件不是子组件,也不是要滚动到的元素组件的父组件
  • 哦,您想在单击按钮/菜单项时有条件地呈现组件吗?请确认是否是这种情况
  • 我想在单击水平菜单元素的元素时滚动到页面元素,例如单页投资组合菜单“关于我、技能、工作”,然后在单击菜单时自动滚动油菜
  • 哇,真的,您是否尝试过为此使用锚标签?使用 id 标识目标,然后放置一个锚标记,其 href 具有预期的 id 的键作为值。像这样:w3docs.com/snippets/html/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 2020-03-14
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
相关资源
最近更新 更多