【问题标题】:How to make ScrollView only scroll when child size is larger in React Native如何使 ScrollView 仅在 React Native 中的子大小较大时滚动
【发布时间】:2019-06-09 23:52:57
【问题描述】:

你好吗。

我想做一个固定高度的组件。

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

这可能吗?

谢谢

【问题讨论】:

  • 嗯,如何获取子组件高度,将其与父级固定高度进行比较,并在您的状态下设置一个布尔值,通过其scrollEnabled 属性控制您的 ScrollView?
  • 我考虑过,但是在render函数中不能setState,只能在render函数中获取child height。
  • 我不这么认为。看看这个answer

标签: react-native scrollview


【解决方案1】:

您可以根据某些条件渲染普通视图或滚动视图,请考虑以下示例:

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 道具的更多信息。

如果您不能或不想使用视图,那么您将不得不进行一些其他类型的布局计算。一种方法是操纵您的样式和 children 道具:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 2021-01-20
    • 2016-08-11
    • 2021-09-08
    • 2020-01-08
    • 2017-10-02
    • 2011-04-13
    • 2022-10-01
    相关资源
    最近更新 更多