首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用window.scrollTo滚动到div的reactjs粘性导航条不起作用

使用window.scrollTo滚动到div的reactjs粘性导航条不起作用
EN

Stack Overflow用户
提问于 2019-07-25 07:01:05
回答 3查看 2.7K关注 0票数 4

我有一个导航条函数组件,它通过onclick回调将链接的名称传递给父组件,并进一步传递给主app组件。app组件有一个具有链接名称的对象和相关的参考文件。应用程序组件中的onclick回调根据底层组件传递给它的链接名从对象中获取引用,并调用一个window.scrollTo。当您第一次单击某个链接时,当页面滚动(如果从粘稠的导航栏单击另一个链接)时,window.scrollTo工作,窗口不再滚动,而是返回到(0,0),然后单击相同的链接即可。

//回调App组件。

代码语言:javascript
运行
复制
manageContent(link){

   console.log(this.linksData[link].current)

    window.scrollTo({
        top: this.linksData[link].current.offsetTop,
        left: 0,
        behavior: 'smooth'
     })    
}

上面的函数被传递给标头组件。

代码语言:javascript
运行
复制
<Header links={data} onclick={this.manageContent} ref={this.headerRef}/>

在标头链接中,使用NavLink函数组件创建链接,其中onClick将返回链接名。

我所做的错误,为什么scrollTo工作在第二次点击一旦页面滚动到顶部,而不是从页面的中部或滚动的位置。

我也尝试过其他滚动功能,而且只使用scrollTo卷轴,而对于scrollOptions、scrollToView、moveTo等,这些功能根本不起作用。

我在控制台中打印出了offsetTop并触发了window.scrollTo(0,“在控制台中打印的offsetTop”),工作正常,没有问题。

这是密码。

App.js

代码语言:javascript
运行
复制
class App extends React.Component {

  constructor(props){
    super(props);
    this.manageContent = this.manageContent.bind(this)

    this.state={}
    this.sectionRef1 = React.createRef();
    this.sectionRef2 = React.createRef();
    this.sectionRef3 = React.createRef();
    this.sectionRef4 = React.createRef();
    this.sectionRef5 = React.createRef();    
    this.headerRef = React.createRef();    
    this.heroRef = React.createRef();
  }
  manageContent(key){
    console.log(key)
    this.setState({key:key});
  }

setActivePage = (key) => {
    let refList = [this.sectionRef1,this.sectionRef2,this.sectionRef3,this.sectionRef4,this.sectionRef5]
    console.log(key)
    console.log(refList[key].current)
    if (refList[key].current){
        window.scrollTo({behavior: "smooth",top: refList[key].current.offsetTop})

    }
}
componentDidUpdate(prevProps, prevState) {  
  console.log("comp updated")
  this.setActivePage(this.state.key)
}
/*
componentDidMount(){
  window.addEventListener('scroll', this.scrollListener)
}
componentWillUnmount() {
  window.removeEventListener('scroll', this.scrollListener)
}    
*/
  render(){     
    return (
      <div className="bp-container-full bp-typography" key="app">
        <Header links={data.links} onclick={this.manageContent} ref={this.headerRef}/>
        <main key="main">
            <HeroSection ref={this.heroRef}/>
            <div className="bp-main">
            <section key="home"className="page" ref={this.sectionRef1}>
              <Home/>
            </section>
            <section key="aboutme" className="page" ref={this.sectionRef2}>
              <AboutMe/>
            </section>
            <section key="sitedetails" className="page" ref={this.sectionRef4}>  
              <SiteDetails/>
            </section>
            <section key="contact" className="page" ref={this.sectionRef5}>  
              <ContactForm/>
            </section>
            </div>
        </main>
        <Footer/>  
      </div>
    );
  }

}
export default App;

Header.js

代码语言:javascript
运行
复制
class Header extends React.Component {
    constructor(props) {
        super(props);
        console.log(props)
        this.linkRef = React.createRef()
        this.state = {isOpen:false};
        this.headerRef = React.createRef()
    }

    render() {      
        const navlink = data.links.map((link,key)=>{ 
            return(
            <a href="#" key={link} ref={this.linkRef}
                    className="nav-list-item bp-upper"
                    onClick={() => this.props.onclick(key)}>
                  {link}
            </a>
        )})
        return (
            <header key="header-key" className={classnames("bp-header","bp-header-fixed",
                            {"is-scrolled":this.state.scrolled})} ref={this.headerRef}>
                <button className={classnames("bp-mobile-menu",{"is-open":this.state.isOpen})} onClick={()=>{this.setState({isOpen:!this.state.isOpen})}}>
                  <i className={classnames("fas", {"fa-bars":!this.state.isOpen, "fa-times":this.state.isOpen})}></i>
                </button>                            
                <div className={classnames("nav", "nav-align-centre",{"is-open":this.state.isOpen})}>
                    <nav className="nav-list nav-primary">
                        {navlink}
                    </nav>
                </div>
            </header>
        )
    }
}
export default Header;
EN

Stack Overflow用户

发布于 2019-07-25 07:21:59

根据您提供的代码,还不清楚什么可能是错误的。我的假设是,你指派推荐人或处理回叫的方式有问题。

下面是一个实用的沙箱,它将向您展示您可能需要的所有代码,以便使其工作:https://codesandbox.io/s/navbar-click-scroll-into-section-us8y7

本质上和你的应用程序有相同的布局。我们有一个带有链接的Navbar/Header,当一个链接被单击时,我们触发一个回调并找到相关的ref。然后滚动到与该引用一起分配的部分。

App.js

代码语言:javascript
运行
复制
import React from "react";
import ReactDOM from "react-dom";
import Header from "./Header";
import HowItWorks from "./HowItWorks";
import BrowserCatalogue from "./BrowserCatalogue";
import Contact from "./Contact";
import Woof from "./Woof";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: null
    };
  }
  //refs
  howItWorks = React.createRef();
  browserCatalogue = React.createRef();
  contact = React.createRef();
  woof = React.createRef();

  changeSelection = index => {
    this.setState({
      selected: index
    });
  };

  componentDidUpdate(prevProps, prevState) {
    this.scrollToSection(this.state.selected);
  }

  scrollToSection = index => {
    let refs = [
      this.howItWorks,
      this.browserCatalogue,
      this.contact,
      this.woof
    ];

    if (refs[index].current) {
      refs[index].current.scrollIntoView({
        behavior: "smooth",
        nearest: "block"
      });
    }
  };

  render() {
    return (
      <div className="App">
        <div>
          <Header changeSelection={this.changeSelection} />
        </div>
        <div ref={this.howItWorks}>
          <HowItWorks />
        </div>
        <div ref={this.browserCatalogue}>
          <BrowserCatalogue />
        </div>
        <div ref={this.contact}>
          <Contact />
        </div>
        <div ref={this.woof}>
          <Woof />
        </div>
      </div>
    );
  }
}

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

Header.js

代码语言:javascript
运行
复制
import React from "react";

const Header = props => {
  const { changeSelection } = props;
  return (
    <div
      style={{
        background: "green",
        height: "50px",
        width: "100%",
        position: "fixed",
        top: "0"
      }}
    >
      <span onClick={() => changeSelection(0)}>Working</span>{" "}
      <span onClick={() => changeSelection(1)}>Catalogue</span>{" "}
      <span onClick={() => changeSelection(2)}>Contact</span>{" "}
      <span onClick={() => changeSelection(3)}>Woof</span>
    </div>
  );
};

export default Header;
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57196071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档