在 ScrollView 中自动滚动反应本机



我正在创建聊天应用程序,并希望每次收到新消息时自动滚动到ScrollView底部。

这是我的代码:

<ScrollView>
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => <SenderChatRow data={item} />}
keyExtractor={(item, index) => index}
/>
{this._bookingRequestMessage()}
</ScrollView>

从 React Native 0.41 及更高版本中,您可以使用以下内容:

<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{        
this.scrollView.scrollToEnd({animated: true});
}}>
</ScrollView>

查看文档

更新

正如您提到的,打开键盘时出现问题,首先:

import { Keyboard } from "react-native";

然后使用componentDidMount()

componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', 
this._keyboardDidShow.bind(this));
}

componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow() {
this.scrollView.scrollToEnd({ animated: false })
}

感谢契丹戈迪亚的更新!

用于滚动视图 将此行添加到滚动视图中

<ScrollView
ref={(ref) => this.flatListRef = ref}
contentContainerStyle={{ flex: 1 }}
onContentSizeChange={(width, height) => this.flatListRef.scrollToEnd({ animated: false })}
>

然后从 react-native add 导入键盘,然后将此代码添加到您的脚本中

componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
}
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}

_keyboardDidShow() {
this.scrollView.scrollToEnd({ animated: false })
}

我试图做同样的事情,就像点击一个按钮滚动屏幕一样。

const [offset,setOffset] = useState(0);
const scrollViewRef = useRef();

const scrollDown = () => {
const y = offset + 101;  /// we can get the height from the onLayout in view
scrollViewRef.current.scrollTo({x: 0, y, animated: true});
setOffset(y);
}

return (
<ScrollView ref={scrollViewRef} >
<Button onPress={scrollDown} title="Scroll down" />
<Text>
[ Very long text here where user has to scroll ]
</Text>
</ScrollView>
)

最新更新