英文:
React Native: 'top' property behaving as expected, but 'bottom' isn't
问题
以下是您React Native应用程序中的代码:
<View
style={{
width: 50,
height: 50,
borderWidth: 1,
}}
>
<View style={{
width: 5,
height: 5,
backgroundColor: 'red',
top: 10,
left: 10
}}></View>
</View>
如预期,这将导致以下结果:
然而,如果我将 top
替换为 bottom
,我会得到以下结果:
如果我将子元素更改为 position: absolute
,它将按预期工作:
我想知道的是:
-
为什么第二张图中红色点在黑色正方形上方?
-
由于红色点是黑色正方形的唯一子元素,为什么添加
position: absolute
会改变任何内容? -
为什么
top
在三张图片中都表现如预期,但bottom
仅在第三张图片中表现如预期?
英文:
I have the following code in my React Native app:
<View
style={{
width: 50,
height: 50,
borderWidth: 1,
}}
>
<View style={{
width: 5,
height: 5,
backgroundColor: 'red',
top: 10,
left: 10
}}></View>
</View>
As expected, this results in:
However, if I swap top
for bottom
, I get this:
If I change the child element to position: absolute
, it works as expected:
What I Want To Know:
-
Why does the red dot go above the black square in the second image?
-
Since the red dot is the only child of the black square, why does adding
position: absolute
change anything? -
Why does
top
behave as expected in all three images, butbottom
behaves as expected only in the third?
答案1
得分: 2
在React-Native中,每个布局元素默认都是相对定位的,因此距离容器初始位置的底部相对位置为10px,这是正确的行为。
如果要将小圆点相对于容器的边界定位,将子元素的位置设置为绝对定位。
<View
style={{
width: 50,
height: 50,
borderWidth: 1,
position: 'relative' // 默认情况下是相对定位
}}
>
<View
style={{
width: 5,
height: 5,
backgroundColor: "red",
bottom: 10,
left: 10,
position: 'absolute'
}}
/>
</View>
英文:
In React-Native, every layout element is relatively positioned by default, so 10px relatively from the bottom of initial position lays out of the container, it is proper behavior.
Set the child's position to absolute, if You want to position the dot against the bounds of the container.
<View
style={{
width: 50,
height: 50,
borderWidth: 1,
position: 'relative' // by default anyway
}}
>
<View
style={{
width: 5,
height: 5,
backgroundColor: "red",
bottom: 10,
left: 10,
position: 'absolute'
}}
/>
</View>
答案2
得分: 2
-
因为没有指定
position: absolute
,所有位置命令都是相对于元素初始位置的。 -
它改变了位置命令(top、left、right、bottom)相对于父元素的解释方式。
-
因为
top
无论position
如何设置,都指向相同位置,但bottom
可能根据position
设置为相对或绝对而指向不同位置。
英文:
-
Because without specifying
position: absolute
all position commands are relative to where the element is initially. -
It changes how the positions commands (top, left, right, bottom ) are interpreted relative to the parent element
-
Because
top
refers to the same place regardless of whatposition
is set to, butbuttom
could refer to a different place depending on if you haveposition
set to relative or absolute
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论