javascript 在 React Native 的 ScrollView 中设置 contentInset 和 contentOffset
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46413642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set contentInset and contentOffset in React Native's ScrollView
提问by Jamgreen
I am trying to make my content start 100 px from the top in React Native. I have tried with
我试图让我的内容从 React Native 的顶部开始 100 像素。我试过
const OFFSET = 100
const ScrollViewTest = (props) => (
<ScrollView
contentInset={{ top: OFFSET }}
contentOffset={{ y: OFFSET }}
>
<Text>Test</Text>
</ScrollView>
)
But when I render the screen, it starts from 0 px, but if I scroll a little, it will scroll to 100px from the top and stay there.
但是当我渲染屏幕时,它从 0 像素开始,但是如果我滚动一点,它会从顶部滚动到 100 像素并保持在那里。
So it seems React Native doen't trigger the contentOffsetand contentInsetproperties on initialization.
所以看起来 React Native 不会在初始化时触发contentOffset和contentInset属性。
How can I fix this? I have also tried setting automaticallyAdjustContentInsets={false}with no changes.
我怎样才能解决这个问题?我也尝试过automaticallyAdjustContentInsets={false}不做任何更改的设置。
Also, it seems these properties are for iOS only. Are there any similar properties for Android?
此外,这些属性似乎仅适用于 iOS。Android 有没有类似的属性?
回答by Peter Theill
You should use the contentContainerStyle1property with a marginTopon your ScrollView.
您应该在 ScrollView 上使用带有 a的contentContainerStyle1属性marginTop。
By using this property it will apply the container wrapping your children (which I believe is what you want in this case) and with the additional benefit of working on both iOS and Android.
通过使用此属性,它将应用包装您的孩子的容器(我相信在这种情况下这是您想要的),并具有在 iOS 和 Android 上工作的额外好处。
I.e.
IE
const OFFSET = 100
const ScrollViewTest = (props) => (
<ScrollView
contentContainerStyle={{ marginTop: OFFSET }}
>
<Text>Test</Text>
</ScrollView>
)
回答by James Kuang
componentDidMount(){
if(Platform.OS==='ios'){
this.refs._scrollView.scrollToOffset({animated:false,offset:-OFFSET});
}
}
render(){
return(
<ScrollView
ref="_scrollView"
contentInset={{top: OFFSET}}
...>
...
</ScrollView>
)
}
回答by yuanwy
When I try to call scrollTo from componentDidMount method it does not scroll. I have to use workaround with setTimeout to make it work:
当我尝试从 componentDidMount 方法调用 scrollTo 时,它不会滚动。我必须使用 setTimeout 的解决方法才能使其工作:
componentDidMount() {
setTimeout(() => this.refs._scrollView.scrollTo({ x: 100, y: 0 }) , 0);
}
回答by Alexander Vitanov
padding-like effect:
填充效果:
const OFFSET = 100
const ScrollViewTest = (props) => (
<ScrollView>
<View style={{ height: OFFSET }} />
<Text>Test</Text>
</ScrollView>
)
header-like effect:
头部效果:
const OFFSET = 100
const ScrollViewTest = (props) => (
<View style={{ paddingTop: OFFSET }}>
<ScrollView>
<Text>Test</Text>
</ScrollView>
</View >
)

