【问题标题】:How to go to last element in react?如何去反应的最后一个元素?
【发布时间】:2021-01-03 14:34:01
【问题描述】:

我尝试了scrollIntoView 并使用了.lastchild,但我无法查看最新评论。用过window.scrollTo也找不到解决办法。

任何人都可以对可行的方法提出一些建议吗?

     const click = () => {
                fetch('url')
                .then(res => res.json())
                .then(data => {
                    if (data.affectedRows > 0) {
                       var element = document.getElementById("txt").lastChild;
                        element.scrollIntoView({behavior: "smooth", block: "end", inline: "center"});
                 }
            })
        }         
}

 {getComment.map(cmnt =>
                        <div key={cmnt.comment_id} className="article-comments-reply">
                            <div className="text-box" id="txt">
                                <h3>{cmnt.username}</h3>
                                <div className="reply-box">
                                    <h4>{cmnt.comment_text}</h4>
                                </div>
                            </div>
                        </div>
)}

【问题讨论】:

标签: javascript reactjs api fetch reload


【解决方案1】:

您不需要使用最后一个孩子。使用工具通过选择器获取元素也不是 React 中的最佳解决方案。

只需将父元素的scrollTop 设置为其height。 它看起来像这样:

ref.current.scrollTop = ref.current.scrollHeight;

这个ref 应该指向你的父组件,这段代码被包裹在其中:

{getComment.map(cmnt =>
  <div key={cmnt.comment_id} className="article-comments-reply">
      <div className="text-box" id="txt">
          <h3>{cmnt.username}</h3>
          <div className="reply-box">
              <h4>{cmnt.comment_text}</h4>
          </div>
      </div>
  </div>
)}

如果你想通过js添加scrollBehavior,你可以这样使用:

ref.current.style.scrollBehavior = 'smooth';

因此,它可以很容易地转换为custom hook,可以对任何元素进行平滑滚动。

自定义钩子useScrollToBottom.

export const useScrollToBottom = (ref) => {
  const scrollToBottom = () => {
    ref.current.style.scrollBehavior = 'smooth';
    ref.current.scrollTop = ref.current.scrollHeight;
  };

  return {
    scrollToBottom,
  }
}

使用

// ...
const ref = useRef();
const {scrollToBottom} = useScrollToBottom(ref);

useEffect(() => {
  // scroll when you need
  scrollToBottom();
}, []);

return (
  <div ref={ref} className="list">
    {
      // some elements
    }
  </div>
)
// ...

【讨论】:

猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 2015-04-03
  • 1970-01-01
  • 2013-04-11
  • 2017-11-28
  • 1970-01-01
相关资源
最近更新 更多