NextJS 在不同 js 文件中存在的按钮 OnClick 上滚动到特定组件的视图

Zoi*_* K. 2 reactjs material-ui next.js

我正在使用 NextJS,我的组件位于不同的 js 文件上,这些文件汇集在我的“pages”文件夹(index.js)上的一个 js 文件下。我想要做的是单击标题/导航栏上的按钮,然后滚动到另一个 js 文件中的组件视图。(我对 NextJS、React hooks 等真的很陌生)尝试在我想要滚动的组件中使用 href={myRef},但包含它的文件给出了一个引用错误“myRef 未定义”。另外,尝试了 document.getElementById 等,但当然它不起作用,因为 NextJS 是服务器渲染的。

我的组件被包装到函数中,因此是函数式组件。

<Button
              variant="outlined"
              size="small"
              onClick={doSomethingAndScrollThere}
              sx={{
                background: "rgba(196, 196, 196, 0.3)",
                border: "none",
                display: { xs: "none", sm: "block" },
                "&:hover": {
                  border: "1px solid black",
                  background: "rgba(196, 196, 196, 0.3)",
                },
              }}
            >
              <Typography
                variant="subtitle2"
                sx={{ color: "black", textTransform: "Capitalize" }}
              >
                Contact me
              </Typography>
            </Button>
Run Code Online (Sandbox Code Playgroud)

我也在使用 Material UI。这是嵌套在我的导航栏中的按钮。这是我想要滚动到的组件。(请注意,该框组件也嵌套在网格组件内)

import * as React from "react";
   import Typography from "@mui/material/Typography";
import Box from "@mui/material/Box";

const ContactBox = () => {
  return (
    <React.Fragment>
      <Box
        id="contactBox"
        sx={{
          background: "rgba(196, 196, 196, 0.3)",
          border: "none",
          borderRadius: "40px",
          justifyContent: "center",
          padding: "20px",
        }}
      >
        <Typography variant="h5">Contact info</Typography>
        <Typography variant="subtitle1">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum.
        </Typography>
      </Box>
    </React.Fragment>
  );
};
export default ContactBox;
Run Code Online (Sandbox Code Playgroud)

上方是 box_component 的 file.js,下方是包含 box_component 的网格组件的 file.js:

<Grid item xs={8}>
      <ContactBox />
    </Grid>
Run Code Online (Sandbox Code Playgroud)

在最后一部分中添加整个代码是没有意义的。提前感谢您的回答,对我宽容一点,正如我所说,我仍在学习。

Gau*_*rav 15

为了平滑滚动到页面上的某个部分,您可以实现以下操作:-(注意:在我的网站https://oculiv.com上实现了完全相同的解决方案)

// your navbar component with menu/button (maybe header.js)

// A scroller function that takes element id and smooth scrolls to it.
const scroll2El = elID => {
    window.scrollTo({
      top: document.getElementById(elID).offsetTop - 60,
      behavior: 'smooth',
    });
  };

const onBtnClick = (e) => {
    e.preventDefault();
    const goto = e.target.getAttribute('goto');
    setTimeout(() => {
      scroll2El(goto);
    }, 100);
  }

...
// goto props should get the same value as the id of the element it scrolls to
<button goto="contacts" onClick={onBtnClick}>Contact</button >
...
Run Code Online (Sandbox Code Playgroud)
// your Contact Component file
// Contact.js

<section id="contacts" />
Run Code Online (Sandbox Code Playgroud)

该解决方案几乎适用于任何前端 JS 框架/库


Zoi*_* K. 5

@dharman 的回答这样帮助了我:onClick={() => router.push("/#contactBox")}在我的按钮内添加了我的功能组件内的这段代码(在本例中是我的顶部栏/导航栏),const router = useRouter()并且这个import { useRouter } from "next/router";在顶部!

如果我也能顺利滚动就太好了!感谢您的帮助!