React Native Flexbox 如何垂直对齐项目?

4

我有点困惑为什么这个flex布局无法正常工作。

 <View
style={{
    display: "flex",
    flexWrap: "wrap"
}}
>
<View style={{ width: "40%", alignSelf: "flex-start" }}>
    <Button BUY</Button>
    <View style={{ alignSelf: "center", marginTop: "2%" }}>// A logo</View>
</View>
<View style={{ width: "40%", alignSelf: "flex-end" }}>
    <AreaChart
        style={{ height: 250 }}
        dataPoints={data}
        contentInset={{ top: 30, bottom: 30 }}
        curve={shape.curveNatural}
        svg={{
            fill: "rgba(134, 65, 244, 0.2)",
            stroke: "rgb(134, 65, 244)"
        }}
    />
</View>
</View>;

我希望得到的布局是:

BUTTON  |   <CHART
LOGO    |   CHART>
和标志位于中心,图表占据右侧的两个"框"。
然而,上述标记生成以下内容:
BUTTON |
LOGO   |
       | CHART
       | CHART

他们做的是正确的事情,但图表的起始点从标志结束的地方开始。

我在使用 flexbox 时哪里出错了?如何得出正确的布局?


1
寻求代码帮助的问题必须在问题本身中包含最短的代码以便复现,最好使用Stack Snippet。请参阅如何创建一个最小、完整和可验证的示例 - Paulie_D
我们需要输出HTML和CSS。 - Paulie_D
1个回答

7
作为React Native中默认的flexDirectioncolumn,因此flex项目将垂直堆叠,因此图表将在自己的行上呈现。
通过在第二个子View上使用alignSelf:"flex-end",对于columns控制交叉轴(水平),它将右对齐。
要使它们并排对齐,请在父View中添加flexDirection:"row"除非您希望第二个ViewalignSelf:"flex-end")对齐到底部,否则可以删除两个子View上的alignSelf属性。 更新后的代码示例
<View style={{
    display: "flex",
    flexDirection: "row",
    flexWrap: "wrap"
}}>
    <View style={{width: "40%"}}>
        <Button
            BUY
        </Button>
        <View style={{alignSelf: "center", marginTop: "2%"}}>
            // A logo
        </View>
    </View>
    <View style={{ width: "40%"}}>
        <AreaChart
            style={{height: 250}}
            dataPoints={data}
            contentInset={{top: 30, bottom: 30}}
            curve={shape.curveNatural}
            svg={{
                fill: 'rgba(134, 65, 244, 0.2)',
                stroke: 'rgb(134, 65, 244)',
            }}
        />
    </View>
</View>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接