gpt4 book ai didi

javascript - 使用向下滚动代码时出现 'Cannot read property scrollIntoView of null' 错误

转载 作者:行者123 更新时间:2023-12-03 18:53:15 27 4
gpt4 key购买 nike

上面的错误经常出现在下面的代码中

 const [consumerMessages, setConsumerMesssages] = useState([])

const messagesEndRef = useRef(null);

const scrollToBottom = () => {
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
};

useEffect(() => {
scrollToBottom()
}, [consumerMessages]);
以下是代码框链接: https://codesandbox.io/s/sleepy-nobel-kt87m
为什么会发生此错误,什么可能是适当的解决方案?

最佳答案

问题
基本上在初始渲染时,ref 没有作为当前 ref 值附加到 DOM 节点,所以 messagesEndRef.current尚未定义。
解决方案
使用空检查:

messagesEndRef.current &&
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
或使用 Optional Chaining Operator ( ?.):
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
演示
Edit getting-error-as-cannot-read-property-scrollintoview-of-null-when-used-scroll

关于javascript - 使用向下滚动代码时出现 'Cannot read property scrollIntoView of null' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66513961/

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