使用reactJs中的id滚动到特定的div而不使用任何其他库 [英] Scroll to a particular div using id in reactJs without using any other library
问题描述
在不使用任何其他库的情况下,在反应中使用id滚动到特定的div,我发现一些他们在使用滚动库的解决方案
Scroll to a particular div using id in react without using any other library, I found a few solutions they were using scroll libraries
这是我的 WrappedQuestionFormFinal 组件中的div代码
here's the div code in my WrappedQuestionFormFinal component
<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>
这是一个通过此组件在此处调用的嵌套组件
it's a nested component called through this component here
<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标签
the problem I'm facing is this form has around 10 questions and in case of submission when error occurs I've to scroll the page where error occurs. the Id is given to h1 tag which is unique
推荐答案
I use a react ref and element.scrollIntoView
to achieve this.
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>
);
}
}
Here's a sample codesandbox that demonstrates clicking a button and scrolling an element into view.
这篇关于使用reactJs中的id滚动到特定的div而不使用任何其他库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!