【发布时间】:2022-10-01 00:08:19
【问题描述】:
我的应用程序中有一个 cmets 列表,我希望当用户访问通知时,应用程序会自动滚动到评论。
我的代码是这样的:
cmets.tsx
const scrollViewRef = useRef(null)
const commentRef = useRef(null)
useEffect(() => {
if(scrollViewRef.current && commentRef.current)
commentRef.current?.measureLayout(
scrollViewRef.current,
(x, y) => {
scrollViewRef.current.scrollTo({x: 0, y, animated: true})
}
)
}, [scrollViewRef.current, commentRef.current])
<ScrollView ref={scrollViewRef}>
...
<Comments>
{comments.map(comment => {
<Comment ref={commentId === commentIdNotification ? commentRef : null} />
)}
</Comments>
</ScrollView>
问题是 measureLayout 值通常是错误的,不会去评论。我认为这是渲染的问题,因为组件向 API 发出了多个请求,并且需要一段时间才能完成渲染。
我怎么解决这个问题?
标签: javascript react-native react-hooks scrollview hook