我正在尝试调用一个将在 onFocus on 上触发的函数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;
上面的组件可以工作并且可以滚动,但需要花费很多时间......我正在使用setTimeout
因为如果没有它,它只会向下滚动屏幕而不计算键盘的高度,因此它不会向下滚动足够多,即使当我继续打字(并触发输入焦点)时,它仍然不会一直向下滚动。
我现在正在处理这个问题,我确实设置了windowSoftInputMode
to adjustResize
我确实经历了一些模块,比如react-native-keyboard-aware-scroll-view
or react-native-auto-scroll
但他们都没有真正完成我需要的工作。
任何如何以正确的方式完成它的指示将不胜感激。谢谢!
而不是使用setTimeout
你用键盘API https://facebook.github.io/react-native/docs/keyboard.html#addlistener反应本机。您为键盘显示添加事件侦听器,然后将视图滚动到末尾。如果您的组件中有多个输入,您可能需要创建一些输入集中的逻辑,但如果您只有一个输入,则可以像下面的示例一样执行此操作。
另一件好事是将你的引用更改为功能引用,因为字符串引用被认为是遗留的,并将在未来版本的 React 中删除。更多信息here https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs.
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)