React.js useRef / createRef当前始终为null滚动

问题描述

我在将引用分配给div时遇到问题。我想滚动到div以供参考,但是.current的值始终为null / undefined。

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始终为空。

enter image description here

反应:16.13.1 单击工具栏上的“联系人”时,我想滚动到<div className={classes.Contact} ref={ref}>

编辑: 我目前在scrollToRef()处有参考,但是window.scrollTo()仍然无法正常工作。<Aux>可能会伤害某些东西吗?也许问题在于重新渲染DOM?早些时候,我尝试使用缓和效果,但是它也无法正常工作。当我在调试过程中取消选中复选框时,它会运行,但是当我打开新的重叠窗口时,它不会触发。

解决方法

您将变量setRef传递给函数(newRef),但是在函数定义中,您将(props)写为变量。因此您需要将功能更改为:

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

我希望它会有所帮助:)

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

,

我建议也使用forwardRef,而不是直接在jsx中调用函数,而应使用生命周期挂钩,例如useEffectcomponentDidUpdate

这是使用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" />

,

好的,问题已解决。

我更改了componentDidMount:

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