【发布时间】:2018-07-03 02:34:59
【问题描述】:
"alignSelf 控制子级在交叉方向上的对齐方式,覆盖父级的 alignItems。它的工作方式类似于 CSS 中的 align-self(默认值:自动)。"
默认的“alignItems”是“stretch”,因此默认情况下视图中的元素应该尝试拉伸到全宽。将“alignSelf”设置为“flex-start”理论上应该会导致项目不拉伸,并出现在最左侧。
这对<Text> 元素按预期工作,为什么它对<Button> 不起作用?
从一个基本前提的例子开始:
<View style={{ flex: 1, flexDirection: "column", backgroundColor: "red" }}>
<Text style={{ backgroundColor: "blue" }}>Hello</Text>
</View>
^ 蓝色文本元素是屏幕的整个宽度
<View style={{ flex: 1, flexDirection: "column", backgroundColor: "red" }}>
<Button style={{ backgroundColor: "blue", alignSelf: "flex-start" }}>Hello</Text>
</View>
^ 蓝色文本元素在最左边,只有其文本的宽度
<View style={{ flex: 1, flexDirection: "column", backgroundColor: "red" }}>
<Button style={{ }} title="here" />
</View>
^ 按钮元素是屏幕的全宽
<View style={{ flex: 1, flexDirection: "column", backgroundColor: "red" }}>
<Button style={{ alignSelf: "flex-start" }} title="here" />
</View>
^ 按钮元素仍然是屏幕的整个宽度
我需要覆盖视图的 alignItems 拉伸(默认),因为视图中还有许多我想拉伸的元素。因此,使用默认行为“拉伸”会更方便。
这个演示展示了 Button 如何对“alignSelf”有零尊重:
<View>
<View style={{ flex: 1, flexDirection: "column", alignItems: "stretch", backgroundColor: "red" }}>
<Text style={{ alignSelf: "flex-start", backgroundColor: "green" }}>don''t stretch me</Text>
<Text style={{ backgroundColor: "green" }}>stretch me</Text>
<Button style={{ alignSelf: "flex-start" }} title="don't stretch me" />
<Button style={{}} title="stretch me" />
</View>
<View style={{ flex: 1, flexDirection: "column", alignItems: "flex-start", backgroundColor: "red" }}>
<Text style={{ backgroundColor: "green" }}>don''t stretch me</Text>
<Text style={{ alignSelf: "stretch", backgroundColor: "green" }}>stretch me</Text>
<Button style={{}} title="don't stretch me" />
<Button style={{ alignSelf: "stretch" }} title="stretch me" />
</View>
</View>
渲染:
| don't stretch me |
| stretch me |
[ DON'T STRETCH ME ]
[ STRETCH ME ]
| don't stretch me |
| stretch me |
[ DON'T STRETCH ME ]
[ STRETCH ME ]
【问题讨论】:
标签: react-native