我在React Native的项目中工作,我想设置我的ScrollView
位置。所以我搜索并发现我们应该使用scrollTo
执行此操作,但我有一个错误:
TypeError: Cannot read property 'scrollTo' of undefined
我的代码:
export default class Index_calendar extends Component {
componentDidMount() {
const _scrollView = this.scrollView;
_scrollView.scrollTo({x: 100});
}
render() {
return (
<ScrollView ref={scrollView => this.scrollView = scrollView}>
{this.renderCalandar()}
</ScrollView>
);
}
}
答案 0 :(得分:1)
您似乎做出了正确的参考。但我建议初始化引用并使其不易出错:
export default class Index_calendar extends Component {
constructor(props) {
super(props);
this.scrollView = null;
}
componentDidMount() {
const _scrollView = this.scrollView;
if (_scrollView) {
_scrollView.scrollTo({x: 100});
}
}
答案 1 :(得分:1)
为什么不在render方法中滚动?
export default class Index_calendar extends Component {
constructor(props) {
super(props);
this.scrollView = null;
}
render() {
return (
<ScrollView ref={scrollView => {
//Sometimes ref can be null so we check it.
if(scrollView !== null && this.scrollView !== scrollView){
this.scrollView = scrollView
scrollView.scrollTo({x: 100});
}}>
{this.renderCalandar()}
</ScrollView>
);
}
}
答案 2 :(得分:1)
您可以使用InteractionManager
解决此问题。
例如
InteractionManager.runAfterInteractions(() => this.scroll.current.scrollTo({ x }));
答案 3 :(得分:0)
我找到了解决方案!我们需要像这样使用setTimeout:
setTimeout(() => {
this.scrollView.scrollTo({x: 100});
}, 1);
答案 4 :(得分:0)
InteractionManager.runAfterInteractions(() => {
this.scrollRef.scrollTo({
x: 0,
y: 0,
animated: true,
});
});
这对我有用,将滚动条重置为顶部