简体   繁体   English

使用 React Hooks 渲染时如何使页面自动滚动到组件

[英]How to make page scroll automatically to components when rendered using React Hooks

I'm new to coding and been working with this simple portfolio page logic:我是编码新手,一直在使用这个简单的投资组合页面逻辑:

codesandbox代码沙盒

By using useRef and use effect hooks, I've got into a point in which the logic in child component scrolls the page to the most recent useRef value.通过使用 useRef 和 use effect hooks,我进入了一个点,即子组件中的逻辑将页面滚动到最近的 useRef 值。

Now when the buttons are being pushed several times, the useRef value stops updating.现在,当按钮被多次按下时, useRef 值将停止更新。 For example, when the "things" button is pressed, it stays in that value and scrolls towards it with every button.例如,当“事物”按钮被按下时,它会保持在那个值,并随着每个按钮向它滚动。

There's also a second problem in which the pages that are rendered on top of the homepage are being scrolled to top immediately without the scrollIntoView animation.还有第二个问题,在主页顶部呈现的页面在没有 scrollIntoView 动画的情况下立即滚动到顶部。 Is there a way to lock a certain height when components are rendered on the top side?当组件在顶部渲染时,有没有办法锁定一定的高度?

Also, I'm aware of my bad habit of duplicating the same logic for every button and state.另外,我知道我为每个按钮和状态复制相同逻辑的坏习惯。 How could I work around this to make it more DRY?我怎样才能解决这个问题,使它更干燥?

I created one method to change state, please let me know if there will be any confusion.我创建了一种改变状态的方法,如果有任何混淆,请告诉我。 Here you can see example for scrolling part How to Scroll to Item in React .在这里你可以看到滚动部分的示例如何在 React 中滚动到项目

import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

import Portfolio from "./portfolio";
import Things from "./things";
import Contact from "./contact";
import About from "./about";

function App() {
  const [showContent, setShowContent] = useState({
    about: false,
    contact: false,
    portfolio: false,
    things: false
  });

  const showRuntimeContent = modelName => {
    if (modelName) {
      setShowContent({[modelName]: !showContent[modelName]});
    }
  };

  return (
    <div className="home">


      <div className="container">
        <button onClick={() => showRuntimeContent("contact")}>Contacts</button>
        <button onClick={() => showRuntimeContent("portfolio")}>Portfolio</button>
        <button onClick={() => showRuntimeContent("about")}>About</button>
        <button onClick={() => showRuntimeContent("things")}>Things</button>

        <h1> HOME</h1>
      </div>
      <div>
      {showContent.contact ? <Contact /> : null}
      {showContent.portfolio ? <Portfolio /> : null}
      {showContent.about ? <About /> : null}
      {showContent.things ? <Things /> : null}
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM