【问题标题】:React.js useRef / createRef current is always null scrollingReact.js useRef / createRef 当前始终为空滚动
【发布时间】:2020-10-10 19:27:33
【问题描述】:

我在分配对 div 的引用时遇到问题。我想滚动到该引用的 div,但 .current 的值始终为空/未定义。

import React, { Component, useRef, useEffect } from 'react';
import { Route, BrowserRouter, Redirect } from 'react-router-dom';

class App extends Component {

    myRef = React.createRef();

  componentDidMount() {
    { this.myRef ? this.scrollToRef() : null }
  }

  scrollToRef = () => {
    if(this.myRef.current !== null) 
    // window.scrollTo(0, this.myRef.current.offsetTop);
    window.scrollTo({ behavior: 'smooth', top: this.myRef.current.offsetTop })
  }

  render() {
    return (
<Aux>
      <BrowserRouter>
        <Route
          path="/contact"
          render={() => (
            <Main
              page={<HomePage />}
              tools={<Toolbar />}
              content={
                <Contact ref={this.myRef} />
              }
            />
          )}
        />
      </BrowserRouter>
</Aux>
    );
  }
}

内部联系人:

import React, { useRef, Component, createRef } from 'react';
import classes from './contact.module.css';

const contact = React.forwardRef((props, ref) => {
  const newRef = useRef();
  return <div className={classes.Contact} ref={ref}>{props.children}</div>
};

我已经尝试了很多版本,但 .current 总是为空..

反应:16.13.1 当我点击工具栏上的联系人时,我想滚动到&lt;div className={classes.Contact} ref={ref}&gt;。

编辑: 现在在scrollToRef() 我有参考,但window.scrollTo() 仍然不起作用.. 特设&lt;Aux&gt; 是否有可能有害?也许问题在于重新渲染 DOM?早些时候我尝试过使用缓出效果,但它也无法正常工作。它在我在调试期间取消单击复选框时运行,但在我打开新重叠时没有触发。

【问题讨论】:

    标签: javascript reactjs react-router react-ref


    【解决方案1】:

    您将变量(newRef) 传递给函数setRef,但在函数定义中您将(props) 写为变量。所以你需要将函数更改为:

      setReference = (newRef) => {
        this.setState({myRef: newRef})
      }
    

    我希望它会有所帮助:)

    顺便说一句,你最好使用forwardRef - https://reactjs.org/docs/forwarding-refs.html

    【讨论】:

    • 我之前改过,但是忘记贴在这里了。谢谢,但没有帮助。需要尝试forwardRef
    【解决方案2】:

    我建议使用forwardRef,另外,不要直接调用jsx中的函数,而是使用useEffect和componentDidUpdate等生命周期钩子

    这是使用 forwardRef 的代码,您可以看到在这种情况下它是一种更简单的设置方法。

    const Contact = React.forwardRef((props, ref) => {
      return (
        <div className={'Contact'} ref={ref}>
          {props.children}
        </div>
      );
    });
    
    class App extends React.Component {
      contactRef = React.createRef();
      state = {};
    
      scrollToRef = () => {
        if (this.contactRef.current !== null)
          // window.scrollTo(0, this.myRef.current.offsetTop);
          window.scrollTo({
            behavior: 'smooth',
            top: this.contactRef.current.offsetTop,
          });
        console.log(this.contactRef.current);
      };
    
      render() {
        return (
          <div>
            <Contact ref={this.contactRef} />
            <button onClick={this.scrollToRef}>Scroll</button>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
    <div id="root" />

    【讨论】:

    • 根据@ינון רחמים 与 forwardRef 的链接,我更改了我的代码,但它仍然不起作用。我已经编辑了源代码。
    • 您应该将 myRef 传递给联系人组件 - &lt;Contact ref={this.myRef} /&gt;
    • 我已经更新了帖子
    【解决方案3】:

    好的,问题已解决。

    我改变了 componentDidMount :

      componentDidMount() {
        // { this.myRef ? this.scrollToRef() : null }
        this.myRef ? this.myRef.current.scrollIntoView({
          behavior: 'smooth',
          block: 'center',
          inline: 'center'
        })
          : null
      }
    

    【讨论】:

      猜你喜欢
      • 2015-01-31
      • 2021-08-09
      • 1970-01-01
      • 2023-03-31
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多