gpt4 book ai didi

javascript - 在不使用任何其他库的情况下使用 reactJs 中的 id 滚动到特定的 div

转载 作者:行者123 更新时间:2023-11-29 17:39:17 25 4
gpt4 key购买 nike

在不使用任何其他库的情况下使用 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 个问题,如果在发生错误时提交,我必须滚动发生错误的页面。 Id 被赋予 h1 标签,它是唯一的

最佳答案

我使用 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这演示了单击按钮并将元素滚动到 View 中。

关于javascript - 在不使用任何其他库的情况下使用 reactJs 中的 id 滚动到特定的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54142051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com