React,使用Refs来scrollIntoView()不能在componentDidUpdate()上工作

Ram*_*ack 8 javascript reactjs react-redux

我在我的应用程序中使用Redux,在组件内部我希望在商店发生更改时滚动到特定的div标签.我有Redux部分工作,所以它触发componentDidUpdate()方法(我已经路由到这个compoennt视图).据我所知,问题是方法scrollIntoView()无法正常工作cos componentDidUpdate()有一个默认行为,滚动到顶部覆盖scrollIntoView().为了解决这个问题,我在setTimeout中包含了调用scrollIntoView()的函数,以确保不会发生这种情况.我想做的是调用一个preventDefault()或任何其他更优雅的解决方案,但我无法找到触发'scrollTop'事件的位置,我在这里查看了Doc:https://facebook.github. io/react/docs/react-component.html#componentdidupdate 和此函数中传递的参数是componentDidUpdate(prevProps,prevState),因为没有事件我不知道如何调用preventDefault()

我已经按照这个文档:https ://facebook.github.io/react/docs/refs-and-the-dom.html并尝试了人们在这里建议的不同方法:如何滚动div以在ReactJS中可见?

没有什么工作虽然这是我的代码,如果有人有任何提示,谢谢

class PhotoContainer extends React.Component {

  componentDidUpdate(){
    setTimeout(() => {
     this.focusDiv();
    }, 500);

  }
  focusDiv(){
    var scrolling = this.theDiv;
    scrolling.scrollIntoView();

  }

  render() {
    const totalList = [];
    for(let i = 0; i < 300; i += 1) {
        totalList.push(
            <div key={i}>{`hello ${i}`}</div>
        );
    }

  return (
      <div >
          {totalList}
          <div ref={(el) => this.theDiv = el}>this is the div I'm trying to scroll to</div>
      </div>
  )
Run Code Online (Sandbox Code Playgroud)

}; }

Ram*_*ack 5

好的,已经有一段时间了,但我在另一个没有该setTimeOut功能的项目中使用了它,所以我想回答这个问题。由于 Redux 通过 props 传递新的更新,我使用了componentWillRecieveProps()方法而不是componentDidUpdate(),这使您可以更好地控制更新的属性并按预期使用该scrollIntoView()函数。

class PhotoContainer extends React.Component {

  componentWillReceiveProps(newProps) {
    if (
      this.props.navigation.sectionSelected !==
        newProps.navigation.sectionSelected &&
      newProps.navigation.sectionSelected !== ""
    ) {
      this.focusDiv(newProps.navigation.sectionSelected);
    }
  }

  focusDiv(section){
    var scrolling = this[section]; //section would be 'theDiv' in this example
    scrolling.scrollIntoView({ block: "start", behavior: "smooth" });//corrected typo
  }

  render() {
    const totalList = [];
    for(let i = 0; i < 300; i += 1) {
        totalList.push(
            <div key={i}>{`hello ${i}`}</div>
        );
    }

    return (
      <div >
          {totalList}
          <div ref={(el) => this.theDiv = el}>
            this is the div I am trying to scroll to
          </div>
       </div>
         )
      };
    }
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用功能组件,因此无法使用 componentWillRecieveProps,因此我将 setTimeOut 与 0 一起使用。感谢您的提示:) (2认同)