代码之家  ›  专栏  ›  技术社区  ›  Nomura Nori

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

  •  0
  • Nomura Nori  · 技术社区  · 6 年前

    你好吗?

    我想做固定高度的部件。

    它是由ScrollView包装的,如果子级高度小于固定高度,我希望这个ScrollView不滚动。

    有可能吗?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   Robbie Milejczak Diego Felipe    6 年前

    可以基于某些条件呈现普通视图或滚动视图,请考虑以下示例:

    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 component

    推荐文章