在ReactJs中使用id滚动到特定的div,不使用其他任何库

6

在React中,使用id滚动到特定的div而不使用其他库,我找到了一些解决方案,它们都使用了滚动库。

这是我 WrappedQuestionFormFinal 组件中的div代码:

 <div className="form-section">
            <Row>
              <Col xs={24} xl={4} className="form-section-cols">
                <h3 id={id}>
                  {t('QUESTION')} {t(id + 1)}
                </h3>
              </Col>
             </Row>
 </div>

这是一个嵌套组件,通过此组件进行调用

      <WrappedQuestionFormFinal
        allQuestions={questions}
        updateScreenTitle={this.props.updateScreenTitle}
        handleDeleteQuestion={this.handleDeleteQuestion}
        question={questions[q]}
        dublicateQuestion={dubQuestion}
        dependantQuestion={dependant}
        id={i}
        key={i}
        tags={this.props.tags}
        changeOrder={this.changeOrder}
        changeScreenNo={this.changeScreenNo}
      />,

我面临的问题是这个表格有大约10个问题,在提交时如果出现错误,我必须滚动页面到出现错误的位置。 h1标签被赋予唯一的ID。

2个回答

12

我使用 React ref 和 element.scrollIntoView 来实现此功能。

class App extends Component {
  constructor(props) {
    super(props);
    this.scrollDiv = createRef();
  }

  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <button
          onClick={() => {
            this.scrollDiv.current.scrollIntoView({ behavior: 'smooth' });
          }}
        >
          click me!
        </button>
        <h2>Start editing to see some magic happen!</h2>
        <div ref={this.scrollDiv}>hi</div>
      </div>
    );
  }
}

这是一个样例codesandbox,演示了点击按钮并将元素滚动到视图中的过程。


2
这似乎只适用于作为同一组件的一部分呈现的 div。 对于其他组件中的 div,页面会刷新。 - AnthonyT

3

你尝试过使用Ref吗?

 constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

handleScrollToElement(event) {
  if (<some_logic>){
    window.scrollTo(0, this.myRef.current.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref={this.myRef}></div>
    </div>)
}

如果(<某些逻辑>){ } 我该如何通过单击另一个元素使其滚动到一个元素? - Ant
<button onClick={handleScrollToElement}>Click here</button> - kahlan88

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接