首页 > 解决方案 > 我正在尝试使用 React-Native 将按钮放置在屏幕底部,我真的很难理解如何通过 flex 支持正确地做到这一点

问题描述

我正在尝试使用 React-Native 构建一个应用程序,我需要在屏幕底部放置两个按钮。到目前为止,我写了这段代码:

    render() {
        const { subtitle } = this.state;
        return (
            <View style={styles.container}>
                <ActionBar onBackAction={this.backActionHandler} isBackAvailable />
                <View style={styles.contentContainer}>
                    <Text>{subtitle}</Text>
                </View>
                <View style={styles.buttonsContainer}>
                    <Button title="BTN #1" />
                    <Button title="BTN #2" />
                </View>
            </View>
        );
    }

使用这些样式:

    const styles = StyleSheet.create({
        container: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'space-between'
        },
        contentContainer: {
            flex: 1,
            flexGrow: 1,
            backgroundColor: 'purple'
        },
        buttonsContainer: {
            flex: 1,
            justifyContent: 'flex-end',
            flexDirection: 'row',
            marginBottom: 40,
            backgroundColor: 'red'
        }
    });

这是迄今为止的结果......

结果

这就是我想要实现的目标:

结果

谁能指出我的错误在哪里?如果这很重要,则上面的整个屏幕将嵌套在另一个仅具有flex: 1属性的视图中。我试图理解这种弹性概念,但我无法做到这一点。

标签: javascriptreact-native

解决方案


只需将样式更改flex为。当您同时放入and时,可用空间分布在这两个容器之间。但根据您的要求,应该占用所有可用空间。所以,设置为正确。要获得所需的结果集,或者您可以避免使用.0buttonsContainerflex: 1buttonsContainercontentContainercontentContainercontentContainerflex: 1flex: 0buttonsContainerflexbuttonsContainer

在此处阅读有关 flex的更多信息。希望这会有所帮助!


推荐阅读