我正在尝试调用一个函数,该函数将在 onFoucs 上触发,该函数将一直TextInput向下滚动 scrollView(使用scrollToEnd())
所以这是我的类组件
class MyCMP extends Component {
constructor(props) {
super(props);
this.onInputFocus = this.onInputFocus.bind(this);
}
onInputFocus() {
setTimeout(() => {
this.refs.scroll.scrollToEnd();
console.log('done scrolling');
}, 1);
}
render() {
return (
<View>
<ScrollView ref="scroll">
{ /* items */ }
</ScrollView>
<TextInput onFocus={this.onInputFocus} />
</View>
);
}
}
export default MyCMP;
Run Code Online (Sandbox Code Playgroud)
上面的组件可以工作并且它确实滚动但需要很多时间......我正在使用setTimeout它因为没有它它只是在没有计算keybaord的高度的情况下沿着屏幕向下滚动所以它不会向下滚动,即使我继续打字(和触发对输入的关注)它仍然不会一直向下滚动。
我现在正在处理它一些很好的时间,我确实将它设置windowSoftInputMode为adjustResize并且我确实经历了一些模块,例如react-native-keyboard-aware-scroll-vieworreact-native-auto-scroll但它们都没有真正按照我的需要完成工作。
任何如何使它以正确的方式完成的方向都将不胜感激。谢谢!
而不是使用setTimeout您使用react-native 的键盘 API。您为键盘显示添加一个事件侦听器,然后滚动视图以结束。如果您的组件中有多个输入,您可能需要创建一些关注输入的逻辑,但如果您只有一个输入,则可以像下面的示例一样执行此操作。
另一件好事是将您的 refs 更改为功能性的,因为字符串 refs 被认为是遗留的,将在未来的 react 版本中删除。更多信息在这里。
class MyCMP extends Component {
constructor(props) {
super(props);
this.scroll = null;
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
}
_keyboardDidShow() {
this.scroll.scrollToEnd();
}
render() {
return (
<View>
<ScrollView ref={(scroll) => {this.scroll = scroll;}}>
{ /* items */ }
</ScrollView>
<TextInput />
</View>
);
}
}
export default MyCMP;
Run Code Online (Sandbox Code Playgroud)
如果你有一个大数据集,React Native 文档会告诉你使用 FlatList。
为了让它滚动到底部,这对我有用
<FlatList
ref={ref => (this.scrollView = ref)}
onContentSizeChange={() => {
this.scrollView.scrollToEnd({ animated: true, index: -1 }, 200);
}}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11483 次 |
| 最近记录: |