4

我有一个导航栏函数组件,它通过 onclick 回调将链接的名称传递给父组件,并进一步传递给主应用程序组件。应用程序组件有一个带有链接名称和关联引用的对象。应用程序组件中的 onclick 回调根据底层组件传递给它的链接名称从对象中获取 ref,并调用 window.scrollTo。window.scrollTo 在您第一次单击链接时起作用,并且如果从粘性导航栏中单击另一个链接,则当页面滚动时,窗口不会再次滚动,而是返回到 (0,0) 并从那里单击相同链接有效。

//在App组件中回调。

manageContent(link){

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

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

上面的函数传递给 Header 组件

<Header links={data} onclick={this.manageContent} ref={this.headerRef}/>

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

我做错了什么,为什么当页面滚动到顶部而不是从页面中间或滚动位置时,scrollTo 在第二次单击时起作用。

我也尝试了其他滚动功能,但奇怪的是只有 scrollTo 滚动,而带有 scrollOptions、scrollToView、moveTo 等的滚动功能根本不起作用。

我在控制台中打印出 offsetTop 并触发 window.scrollTo(0,"offsetTop print in console"),工作正常,没有问题。

这是代码。

应用程序.js

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;

页眉.js

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;
4

3 回答 3

1

最后在几乎多次编写整个应用程序之后发现了问题。

我的链接有一个 href,是的,我很傻,使用 href="#" 解决了问题,并且可能还解释了为什么它在两次点击而不是 1 中起作用。

<a href="#" key={link} ref={this.linkRef}
                    className="nav-list-item bp-upper"
                    onClick={() => this.props.onclick(key)}>
                  {link}
            </a>
于 2019-07-27T03:36:20.820 回答
0

刚刚发现这个react ref with focus() 没有 setTimeout (我的例子)不起作用,是的,这有帮助。setTimeOut 确实提供了一种修复,但这篇文章对我的代码可能有什么问题也很有意义。

于 2019-07-25T09:37:29.330 回答
0

根据您提供的代码,尚不清楚可能出了什么问题。我的假设是您分配参考或处理回调的方式有问题。

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

本质上与您的应用程序具有相同的布局。我们有一个带有链接的 Navbar/Header,当点击一个时,我们会触发一个回调并找到关联的ref. 然后滚动到分配有该参考的部分。

应用程序.js

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);

页眉.js

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;
于 2019-07-25T07:21:59.500 回答