“alignSelf控制孩子在横向上的排列方式,覆盖父级的alignItems。它的作用类似于CSS中的align-self(默认值:auto)。”
默认的“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>
^按钮元素仍然是屏幕的整个宽度
我需要覆盖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 ]
答案 0 :(得分:1)
现在我在一个视图中包含一个Button。它会完美地运作
<View style = {styles.container}>
<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>
<View style = {{alignSelf:'flex-start'}}>
<Button style={{ alignSelf: "flex-start" }} title="don't stretch me" />
</View>
<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>
<View style = {{alignSelf:'flex-start'}}>
<Button style={{ alignSelf: "flex-start" }} title="don't stretch me" />
</View>
<View style = {{alignSelf:'stretch'}}>
<Button title="stretch me" />
</View>
</View>
</View>
答案 1 :(得分:0)
你输入的样式并不重要&#39;按钮&#39; 它只是不支持&#39; style&#39;支柱。
您必须使用容器(&#39; View&#39;)样式来更改位置。