你好吗。
我想制作具有固定高度的组件。
它由 ScrollView 包装,如果子高度小于固定高度,我希望此滚动视图不会滚动。
这可能吗?
谢谢
您可以根据某些条件呈现普通视图或滚动视图,请考虑以下示例:
class MyComponent extends React.Component {
constructor(props){
super(props)
this.state = {
childHeight: 0,
screenHeight: Dimensions.get('window').height
}
}
render(){
const wrapper = this.state.childHeight > this.state.screenHeight ? ScrollView : View
return (
<Wrapper>
//onLayout passes a an object with a synthetic event that has a nativeEvent prop
//I pull off the nativeEvent prop using deconstruction so I can get the height
<View onLayout={
({ nativeEvent }) => {
this.setState({ childHeight: nativeEvent.layout.height })
}}>
{children}
</View>
</Wrapper>
)
}
}
这只是一种实现,您可以随心所欲地进行。以下是有关 onLayout 道具的更多信息。
如果您不能或不想使用视图,则必须进行其他类型的布局计算。一种方法是操纵您的样式和子道具:
const myStyle = StyleSheet.create({
childStyle: {
height: 180
}
})
class MyComponent extends React.Component {
constructor(props){
super(props)
this.state = {
childHeight: React.Children.count(props.children) * 180,
//get the count of how many children have been passed to your component
//and multiple it by whatever height your children have set in their styles
screenHeight: Dimensions.get('window').height
}
render(){
const wrapper = this.state.childHeight > this.state.screenHeight ? ScrollView : View
return (
<Wrapper>
{children}
</Wrapper>
)
}
}
如果子级的数量可以在多个渲染中发生变化,那么我建议学习 FlatList 组件