React Native中如何让ScrollView只在子尺寸较大时滚动

问题描述 投票:0回答:2

你好吗。

我想制作具有固定高度的组件。

它被 ScrollView 包裹,如果子高度小于固定高度,我希望此滚动视图不滚动。

这可能吗?

谢谢

react-native scrollview
2个回答
3
投票

您可以根据某些条件渲染普通 View 或 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 组件


0
投票

对于 iOS,这是通过

alwaysBounceVertical={false}
实现的 https://reactnative.dev/docs/scrollview#alwaysbouncevertical-ios

© www.soinside.com 2019 - 2024. All rights reserved.