对于类似聊天的应用程序,我希望将ScrollView组件滚动到底部,因为最新的消息显示在较旧的消息下.我们可以调整一个滚动位置ScrollView吗?
Ani*_*vle 131
对于React Native 0.41及更高版本,您可以使用内置scrollToEnd方法执行此操作:
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{
this.scrollView.scrollToEnd({animated: true});
}}>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)
clt*_*ang 42
对于任何编写可以使用钩子的函数组件的人,
import React, { useRef } from 'react';
import { ScrollView } from 'react-native';
const ScreenComponent = (props) => {
const scrollViewRef = useRef();
return (
<ScrollView
ref={scrollViewRef}
onContentSizeChange={() => scrollViewRef.current.scrollToEnd({ animated: true })}
/>
);
};
Run Code Online (Sandbox Code Playgroud)
dri*_*oda 24
使用onContentSizeChange来跟踪滚动视图的底部Y(高度)
https://facebook.github.io/react-native/docs/scrollview.html#oncontentsizechange
var _scrollToBottomY
<ScrollView
onContentSizeChange={(contentWidth, contentHeight)=>{
_scrollToBottomY = contentHeight;
}}>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)
然后使用滚动视图的引用名称
this.refs.scrollView.scrollTo(_scrollToBottomY);
Run Code Online (Sandbox Code Playgroud)
sen*_*tor 20
这是我能想到的最简单的解决方案:
<ListView
ref={ref => (this.listView = ref)}
onLayout={event => {
this.listViewHeight = event.nativeEvent.layout.height;
}}
onContentSizeChange={() => {
this.listView.scrollTo({
y: this.listView.getMetrics().contentLength - this.listViewHeight
});
}}
/>;
Run Code Online (Sandbox Code Playgroud)
fri*_*mle 10
使用用TypeScript编写的函数组件来实现这一点的现代方法:
import {useRef} from 'react';
import {ScrollView, View} from 'react-native';
function App() {
const scrollViewRef = useRef<ScrollView>(null);
// ...
return (
<View>
{/* ... */}
<ScrollView
onContentSizeChange={() => scrollViewRef.current?.scrollToEnd()}
ref={scrollViewRef}
>
{/* ... */}
</ScrollView>
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
如果 2020 年或以后有人想知道如何使用功能组件来实现这一点。这就是我所做的:
ref={ref => scrollView = ref }
onContentSizeChange={() => scrollView.scrollToEnd({ animated: true })}>
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用react-native-invertible-scroll-view模块反转滚动/列表视图,然后只需调用ref.scrollTo(0)滚动到底部。
安装模块:
npm install --save react-native-invertible-scroll-view
Run Code Online (Sandbox Code Playgroud)
然后导入组件:
npm install --save react-native-invertible-scroll-view
Run Code Online (Sandbox Code Playgroud)
然后使用以下 JSX 而不是 a ScrollView:
import InvertibleScrollView from 'react-native-invertible-scroll-view';
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为react-native-invertible-scroll-view翻转整个视图的内容。请注意,视图的子视图也将以与普通视图相反的顺序呈现 - 第一个子视图将出现在底部。
试试这个解决方案
Xcode 10.0
注册护士:56.0.0
<ScrollView ref="scrollView"
onContentSizeChange={(width,height) => this.refs.scrollView.scrollTo({y:height})}> </ScrollView> // OR height - width
Run Code Online (Sandbox Code Playgroud)
Jac*_*ack -2
尝试将滚动视图的contentOffset属性设置为内容的当前高度。
要完成您需要的操作,您可以将其作为 onScroll 事件的一部分来执行。然而,这可能会导致糟糕的用户体验,因此仅在附加新消息时才执行此操作可能会更加用户友好。
| 归档时间: |
|
| 查看次数: |
50831 次 |
| 最近记录: |