如何在React Native中将滚动视图中的视图设置为动态高度。

huangapple go评论64阅读模式
英文:

How to set dynamic height to a view inside a scrollView in reactNative

问题

这是我的代码:

<ScrollView>
  <View>
   <Text1/> 
   <Text2/>
   ... 
  </View>
</ScrollView>

ScrollView 只有在内部的 View 具有特定高度时才能正常工作,但是视图内的对象数量可能会变化,因此高度应相应调整。然而,我不知道如何实现这一点。

我尝试通过将单个文本对象的高度乘以对象的数量来计算高度(它们都具有相同的高度),但似乎高度不足以启用 ScrollView

英文:

This is my code:

&lt;ScrollView&gt;
  &lt;View&gt;
   &lt;Text1/&gt; 
   &lt;Text2/&gt;
   ... 
  &lt;/View&gt;

The ScrollView only works when the View inside has a specific height, but the number of objects inside the view can change, so the height should adjust accordingly. However, I don't know how to do it.

I attempted to calculate the height by multiplying the height of a single text object by the number of objects (they all have the same height), but it seems that the height is not sufficient to activate the ScrollView.

答案1

得分: 0

使用React Native中的flexGrow属性可以实现此行为。

以下是使用具有动态大小的视图的示例。我添加了边框和颜色以便更容易进行可视化。

<ScrollView
  contentContainerStyle={{
    flexGrow: 1,
    borderColor: "green",
    borderWidth: 5
  }}
>
  <View style={{ borderColor: "purple", borderWidth: 5 }}>
    <Text>Hello</Text>
  </View>
  <View style={{ borderColor: "red", borderWidth: 5 }}>
    <Text style={{ fontSize: 30 }}>World</Text>
  </View>
</ScrollView>

如果您需要更多翻译,请告诉我。

英文:

A way to achieve this behavior is by using the flexGrow property in React Native.

Here is an example using views with dynamic sizes. I added borders and colors for easier visualization.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

 &lt;ScrollView
    contentContainerStyle={{
      flexGrow: 1,
      borderColor: &quot;green&quot;,
      borderWidth: 5
    }}
  &gt;
    &lt;View style={{ borderColor: &quot;purple&quot;, borderWidth: 5 }}&gt;
      &lt;Text&gt;Hello&lt;/Text&gt;
    &lt;/View&gt;
    &lt;View style={{ borderColor: &quot;red&quot;, borderWidth: 5 }}&gt;
      &lt;Text style={{ fontSize: 30 }}&gt;World&lt;/Text&gt;
    &lt;/View&gt;
  &lt;/ScrollView&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月12日 21:08:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定