簡體   English   中英

React react-scroll-to(滾動到 Ref 不起作用)

[英]React react-scroll-to (scroll to Ref not working)

我想在單擊按鈕時平滑滾動到特定的參考。 我正在嘗試使用'react-scroll-to' 有一個關於滾動到參考的文檔,我試圖在這里找到解決方案 stackoverflow & github 問題。 但我找不到合適的解決方案。 請幫我解決這個問題。

提前致謝!

我在這里准備了代碼框https://codesandbox.io/s/react-scroll-to-ref-nwpq2?file=/src/index.js

import React from 'react'
import ReactDOM from 'react-dom'
import { ScrollTo } from 'react-scroll-to'

import './styles.css'

class Child1 extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.scrollTo}>Scroll</button>
      </div>
    )
  }
}

class Child2 extends React.Component {
  render() {
    return (
      <div style={{ height: '500px', backgroundColor: 'blue' }}>Child 2</div>
    )
  }
}

class Example extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }
  render() {
    return (
      <div className="App">
        <h1>Index Component</h1>
        <ScrollTo>
          {({ scrollTo }) => {
            console.log(this.myRef)
            return (
              <Child1
                scrollTo={() =>
                  scrollTo({
                    ref: this.myRef,
                    // y: 100,
                    smooth: true
                  })
                }
              />
            )
          }}
        </ScrollTo>
        <Child2 />
        <div
          ref={this.myRef}
          style={{ height: '500px', backgroundColor: 'black' }}
        >
          Hello
        </div>
      </div>
    )
  }
}

const rootElement = document.getElementById('root')
ReactDOM.render(<Example />, rootElement)

我認為您誤解了 scrollTo 的 ref 屬性是如何工作的。 Ref 告訴 scrollTo function 滾動哪個元素,而不是滾動到哪個元素。 為了證明這一點,我制作了一個沙箱的分支並對其進行了一些編輯: https://codesandbox.io/s/react-scroll-to-ref-nl6yz

我會嘗試使用內置的方法而不是這個庫。 此處已對此進行了解釋: https://stackoverflow.com/a/51828976/1779469

正如@sava 提到的,我誤解了 scrollTo 的 ref 屬性是如何工作的。 順便說一句,根據@sava 的回答,我剛剛將我的代碼框修復為滾動到底部參考的 offsetTop 並且它工作順利。

              <Child1
                scrollTo={() =>
                  scrollTo({
                    y: this.myRef.current.offsetTop,
                    smooth: true
                  })
                }
              />

https://codesandbox.io/s/react-scroll-to-ref-nwpq2?file=/src/index.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM