【问题标题】:React react-scroll-to (scroll to Ref not working)React react-scroll-to(滚动到 Ref 不起作用)
【发布时间】:2020-04-17 12:26:36
【问题描述】:

我想在单击按钮时平滑滚动到特定的参考。我正在尝试使用“react-scroll-to” 有一个关于滚动到 ref 的文档,我试图在这里 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)

【问题讨论】:

    标签: javascript reactjs scroll ref


    【解决方案1】:

    我想你误解了 scrollTo 的 ref 属性是如何工作的。 Ref 告诉 scrollTo 函数滚动哪个元素,而不是滚动到哪个元素。为了证明这一点,我对您的沙箱做了一个分支并对其进行了一些编辑:https://codesandbox.io/s/react-scroll-to-ref-nl6yz

    我会尝试使用 react 内置方法而不是这个库。此处已对此进行了解释:https://stackoverflow.com/a/51828976/1779469

    【讨论】:

    • 感谢您的解释。但是有没有办法用这个库将窗口滚动到某个元素?或者你认识谁?
    • 我不认为有什么我能说的,你可能会得到你想要滚动到的元素的 Y 坐标,然后将该坐标传递给滚动函数,但这似乎太乏味了.使用内置方法可能是您最好的选择。
    • 我刚刚修复了我的代码框,以便与当前库正常工作。再次感谢
    【解决方案2】:

    正如@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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 2021-02-23
      • 2021-06-29
      • 2019-04-02
      • 2021-06-24
      • 2019-11-18
      相关资源
      最近更新 更多