如何使ScrollView仅在React Native中子级较大时才滚动

时间:2019-01-15 22:34:56

标签: react-native scrollview

你好吗

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

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

有可能吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以根据某些条件渲染普通视图或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道具的更多信息。

如果您不能或不希望使用View,则必须进行其他某种布局计算。一种方法是操纵您的样式,然后使用儿童道具:

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 component