【问题标题】:Scroll to Top of Page onClick with React使用 React 滚动到页面顶部
【发布时间】:2020-05-14 06:38:33
【问题描述】:

我有一个使用名为#mainView 的静态ID 呈现的组件。我有一个组件在页面下方呈现button 元素,我想在单击按钮时向上滚动到#mainView 元素。据我所知,这是一个非常简单的用户体验,它是 decades now 的 Web 标准的一部分,可以通过普通 HTML 中的简单 <a href="#mainView">...</a> 来完成(并使用 scroll-behavior: smooth 作为实验性功能进行扩展) )。

我花了最后一个小时试图在 React 中复制这种行为,但无济于事。 URL 中的哈希被忽略,Gatsby 抱怨外部链接。我试过@reach/router/navigateLink。我曾尝试使用onClick={...},但手动尝试覆盖onclick 不起作用。这些都不会产生 任何 行为,我可以在 SO 上找到的唯一方法涉及扩展 React.Component 并进入 render(),使用另一种方法,使用 refs,以及各种应该如此简单的 UX 不需要 10,000%。

任何方法让 React 轻松复制我想要的吗?而且,为什么 React 开发人员会积极打破传统的 Web 功能?感谢所有回复。

【问题讨论】:

  • 我投票结束这个问题,因为我自己找到了解决方案。

标签: javascript reactjs


【解决方案1】:

可能不是很好的方法,但您可以尝试使用element.scrollIntoView,在示例中我使用 id 和document.getElementById,但您可以将其替换为ref

const Element = ({id,text})=>(<div id={id} style={{width:"100%", height: "400px", border:"solid 1px black"}} >{text}</div>);

const Scroll = ({to})=><span onClick={()=>document.getElementById(to).scrollIntoView({behavior:"smooth"})} >Scroll</span>

const App = ()=><div>
<h1>MyApp</h1>
<Element id="el-1" text="Lorem Ipsum" />
<Element id="el-2" text="Lorem Ipsum" />
<Element id="el-3" text="Lorem Ipsum" />
<Scroll to="el-2"/>
</div>



ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

是的,如果不是到一个元素,而是到顶部window.scrollTo({top:0,behavior:'smooth'}) 应该就足够了。

【讨论】:

    【解决方案2】:

    我使用的是 Gatsby,解决方法是导入 gatsby-plugin-smoothscroll 包并添加到插件(docs),然后导航:

    <button onClick={() => scrollTo('#mainView')}>My link</button>
    

    【讨论】:

      【解决方案3】:
      class Scroll extends React.Component {
        constructor(props) {
          super(props);
          this.myRef1 = React.createRef();
          this.myRef2 = React.createRef();
          this.myRef3 = React.createRef();
          this.myRef4 = React.createRef();
        }
        scrollSmooth(e, scroll) {
          if (scroll === "sec1") {
            this.myRef1.current.scrollIntoView({
              behavior: "smooth",
              block: "start"
            });
          } else if (scroll === "sec2") {
            this.myRef2.current.scrollIntoView({
              behavior: "smooth",
              block: "start"
            });
          } else if (scroll === "sec3") {
            this.myRef3.current.scrollIntoView({
              behavior: "smooth",
              block: "start"
            });
          } else if (scroll === "sec4") {
            this.myRef4.current.scrollIntoView({
              behavior: "smooth",
              block: "start"
            });
          }
        }
        render() {
          return (
            <div className="container">
              <ul className="list-group">
                <li className="list" onClick={e => this.scrollSmooth(e, "sec1")}>
                  section1
                </li>
                <li className="list" onClick={e => this.scrollSmooth(e, "sec2")}>
                  section2
                </li>
                <li className="list" onClick={e => this.scrollSmooth(e, "sec3")}>
                  section3
                </li>
                <li className="list" onClick={e => this.scrollSmooth(e, "sec4")}>
                  section4
                </li>
              </ul>
              <div className="row">
                <div className="section1" ref={this.myRef1}>
                  <p>Section 1</p>
                </div>
                <div className="section2" ref={this.myRef2}>
                  <p>Section 2</p>
                </div>
                <div className="section3" ref={this.myRef3}>
                  <p>Section 3</p>
                </div>
                <div className="section4" ref={this.myRef4}>
                  <p>Section 4</p>
                </div>
              </div>
            </div>
          );
        }
      }
      
      export default Scroll;
      

      您好,请参阅此组件。 工作链接click here

      【讨论】:

        猜你喜欢
        • 2022-01-09
        • 2010-11-11
        • 1970-01-01
        • 2021-01-29
        • 2020-08-08
        • 1970-01-01
        • 1970-01-01
        • 2022-08-24
        相关资源
        最近更新 更多