简体   繁体   English

React 中的自动滚动 Div

[英]Auto scroll Div in React

I am building an app and users can add comments, I can't get the div to auto scroll to the bottom so when the user comments their latest comment doesn't show unless they scroll as I have overflow-y set to scroll.我正在构建一个应用程序,用户可以添加评论,我无法让 div 自动滚动到底部,所以当用户评论他们的最新评论时不会显示,除非他们滚动,因为我已经设置了溢出-y 滚动。 How could I implement this in React please?请问我如何在 React 中实现这个?

Comments div评论区

<div className = 'comments'>
          {item.comments.map((comment,index) => {
          return <h6 key = {index}><span className ='comment-name'> {comment.postedBy.name} </span> {comment.text}</h6>}
</div>

comments css评论 css

.comments {
  max-height: 20vh;
  overflow-y: scroll;
  padding-left: 1rem;
}

Form submit code表单提交代码

 <form onSubmit = {(e) => {
                            e.preventDefault()
                            makeComment(e.target[0].value, item._id)
                            e.target[0].value = null }
</form>
        

Every library I tried didn't have the desired effect as I have multiple scrollable divs on the page and I couldn't get it to work.我尝试的每个库都没有达到预期的效果,因为我在页面上有多个可滚动的 div,我无法让它工作。

I ended up using the css我最终使用了 css

display: flex;
flex-direction: column-reverse;

This had the effect but the data was then displayed backwards so this little line solved that issue before it was mapped through to display the comments这产生了效果,但数据随后被向后显示,所以这条小线在映射到显示评论之前解决了这个问题

item.comments.slice(0).reverse().map((function...))

Little bit of a 'bodge' but the end result is perfect有点“笨拙”,但最终结果是完美的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM