React native 我想用scrollTo
我在React Native中处理一个项目,我想设置我的React native 我想用scrollTo,react-native,scrollview,React Native,Scrollview,我在React Native中处理一个项目,我想设置我的ScrollView位置。因此,我搜索并发现我们应该使用scrollTo执行此操作,但我有一个错误: 我的代码: export default class Index_calendar extends Component { componentDidMount() { const _scrollView = this.scrollView; _scrollView.scrollTo({x: 100}); } render
ScrollView
位置。因此,我搜索并发现我们应该使用scrollTo
执行此操作,但我有一个错误:
我的代码:
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>
);
}
}
导出默认类索引\u日历扩展组件{
componentDidMount(){
const\u scrollView=this.scrollView;
_scrollView.scrollTo({x:100});
}
render(){
返回(
this.scrollView=scrollView}>
{this.renderCalandar()}
);
}
}
您似乎做了正确的参考。但我建议初始化引用并使其不易出错:
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});
}
}
我找到了解决办法!我们需要像这样使用setTimeout:
setTimeout(() => {
this.scrollView.scrollTo({x: 100});
}, 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>
);
}
}
导出默认类索引\u日历扩展组件{
建造师(道具){
超级(道具);
this.scrollView=null;
}
render(){
返回(
{
//有时ref可以为null,所以我们检查它。
if(scrollView!==null&&this.scrollView!==scrollView){
this.scrollView=滚动视图
scrollView.scrollTo({x:100});
}}>
{this.renderCalandar()}
);
}
}
您可以使用交互管理器来解决此问题。
比如说
InteractionManager.runAfterInteractions(()=>this.scroll.current.scrollTo({x}))代码>
这对我来说很有效,可以将滚动条重置为顶部,希望这会有所帮助。scrollTo
是此解决方案的一部分,但无法可靠地工作。改用InteractionManager.runAfterInteractions
。可能是因为您使用了动画.Scroll?然后就是scroll.current.getNode().scrollTo
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>
);
}
}
InteractionManager.runAfterInteractions(() => {
this.scrollRef.scrollTo({
x: 0,
y: 0,
animated: true,
});
});