单击链接时,React Use ref滚动到特定组件

如何解决单击链接时,React Use ref滚动到特定组件

我想知道如何使用React @{ ViewBag.Title = "Home Page"; } <link rel="stylesheet" href="~/Content/bootstrap-reboot.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script> <link rel="stylesheet" href="~/Content/style.css"> <div class="container-fluid container-xl"> <div class="wrapper"> <!--Sidebar--> <div id="sidebar-wrapper"> <nav id="sidebar" class="col-md-4 col-lg-3 d-md-block bg-light sidebar collapse"> <div class="sidebar-sticky pt-3"> @*SIDEBAR TOGGLE BUTTON*@ <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <button type="button" id="sidebarCollapse" class="btn btn-info" data-toggle="collapse" data-target="#navbar-collapse"> <i class="fas fa-align-left"></i> <span>Toggle Sidebar</span> </button> </div> </nav> @*EXPAND-COLLAPSE ACCORDION*@ <div class="accordion" id="accordion"> <div class="card bg-transparent"> <div class="card-header" id="headingOne"> <h2 class="mb-0 text-center"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> OPTIONS </button> </h2> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <ul class="nav flex-column"> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label text-dark" for="customCheck1">option1</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck2"> <label class="custom-control-label text-dark" for="customCheck2">option2</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck3"> <label class="custom-control-label text-dark" for="customCheck3">option3</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck4"> <label class="custom-control-label text-dark" for="customCheck4">option4</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck5"> <label class="custom-control-label text-dark" for="customCheck5">option5</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck6"> <label class="custom-control-label text-dark" for="customCheck6">option6</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck7"> <label class="custom-control-label text-dark" for="customCheck7">option7</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck8"> <label class="custom-control-label text-dark" for="customCheck8">option8</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck9"> <label class="custom-control-label text-dark" for="customCheck9">option9</label> </div> </li> </ul> </div> </div> </div> </div> </div> @*END OF FIRST CARD*@ <div class="accordion" id="accordion"> @*SECOND CARD*@ <div class="card bg-transparent"> <div class="card-header" id="headingTwo"> <h2 class="mb-0 text-center"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> MORE OPTIONS </button> </h2> <div id="collapseTwo" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <ul class="nav flex-column"> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck10"> <label class="custom-control-label text-dark" for="customCheck10">option10</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck11"> <label class="custom-control-label text-dark" for="customCheck11">option11</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck12"> <label class="custom-control-label text-dark" for="customCheck12">option12</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck13"> <label class="custom-control-label text-dark" for="customCheck13">option13</label> </div> </li> <li class="nav-item"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck14"> <label class="custom-control-label text-dark" for="customCheck14">option14</label> </div> </li> </ul> </div> </div> </div> @*END OF SECOND CARD*@ </div> </nav> <!--End of Sidebar--> </div> <div id="page=content-wrapper"> <div class="col"> <div class="jumbotron jumbotron-fluid" style="background-color: #a5ccf6"> <div class="container-fluid container-lg"> <h1>Headline</h1> <p class="lead">Add your own entries.</p> <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> </div> <div class="row"> <div class="col-md-4"> <h2>HEADLINE1</h2> <p> ASP.NET MVC gives you a powerful,patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable,agile development. </p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>HEADLINE2</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add,remove,and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>HEADLINE3</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div> </div> </div> </div> </div> Thanks a lot. Coby 导航到特定组件

refs

AppHeader

 function App() {
      const CompetencesRef = React.useRef();
      const ExperiencesRef = React.useRef();
      const FormationRef = React.useRef();
      const RecoRef = React.useRef();
    
    
      return (
        <ParallaxProvider>
          <ThemeProvider theme={theme}>
            <div className="App">
    
              <div className="hero">
                <HeaderApp />
                <ApprochApp />
              </div>
              <Apropos />
              <Competences parentRef={CompetencesRef} />
              <Experiences parentRef={ExperiencesRef} />
              <Formation parentRef={FormationRef} />
              <Recom parentRef={RecoRef} />
              <Contact />
              <Footer />
    
            </div >
          </ThemeProvider>
        </ParallaxProvider>
      );
    }

AppMenu

 const AppHeader = () => {
        return (
            <div >
                <Headroom>
                    <MenuApp />
                </Headroom>
    
            </div>
        )
}


   export default AppHeader

我知道我应该在父组件上声明ref,但是我在如何将引用传递给菜单应用程序以及如何在其与组件之间建立链接方面有个困惑。

实际上,我不会使用react-scroll

之类的软件包

解决方法

我认为您需要forwarding-refs

在父母中

const RecoRef = React.useRef();
....
<ChildComponent ref={RecoRef} />

在子组件中

//export the component with React.forwardRefs

const ChildComponent = (props,ref) => {
    return (
        <div ref={ref}>
        .....
        </div>
    )
}

export default React.forwardRefs(ChildComponent)
,

需要两件事:refscrollIntoView。 该片段是在组件之间共享引用的简化版本,滚动到该div的标题中有redDivbutton;我在顶部父元素中创建了ref,然后将它作为道具传递给标头和要滚动到的组件;标题中有一个按钮,该按钮在scrollIntoView上调用ref方法,因此浏览器会将元素滚动到视图中。

const AppHeader = (props) => {
    return (
        <div className="menu sticky-inner grid-container">
            my logo
            <button onClick={()=> props.iconMenuRefs[0].current.scrollIntoView({behavior: "smooth"})}
            > scroll to red div </button>
            <button onClick={()=> props.iconMenuRefs[1].current.scrollIntoView({behavior: "smooth"})}
            > scroll to blue div </button>
        </div>
    )
}

function App() {
  const redDivRef = React.useRef();
  const blueDivRef = React.useRef();
  return (
    <div>
      <AppHeader iconMenuRefs={[redDivRef,blueDivRef]}/>
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <SimpleComp ref={redDivRef} color="red"/>
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <br /><br /><br /><br /><br /><br /><br />
      <SimpleComp ref={blueDivRef} color="blue"/>
    </div>
  );
}

const SimpleComp = React.forwardRef((props,ref) => {
  return <div style={{backgroundColor: props.color}} ref={ref}>scroll to me!</div>
})

ReactDOM.render( <App />,myApp )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.0/umd/react-dom.production.min.js"></script>
<div id="myApp"></div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res