【问题标题】:Flex header layout in React NativeReact Native 中的 Flex 标题布局
【发布时间】:2018-03-10 06:02:27
【问题描述】:

我是 react native 的新手,我试图将后退按钮向左对齐,但将标题保持在中心,但没有任何效果,这是代码。

TouchableOpacity 是返回按钮,Text 是标题,每个都有自己的风格。

import React, { Component } from 'react';
import { View, Text, TouchableOpacity, Image } from 'react-native';
import { Colors } from '../Variables';

class Header extends Component {
    render(){
        return(
            <View style={ styles.headerStyle }>
                <TouchableOpacity>
                    <Image style={ styles.backBtnStyle } source={ require('../graphics/icons/arrow_left_white.png') }/>
                </TouchableOpacity>
                <Text style={ styles.titleStyle }>
                    TITLE
                </Text>
            </View>
        );
    }
}

const styles = {
    headerStyle: {
        backgroundColor: Colors.primary,
        flexDirection: 'row',
        alignItems: 'center',
    },
    backBtnStyle: {
        width: 25,
        height: 25,
        margin: 10,
    },
    titleStyle: {
        color: '#fff',
        textAlign: 'center',
        fontSize: 25,
    }
};

export default Header;

感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs react-native flexbox babeljs


    【解决方案1】:

    你应该尝试查看this document关于 React native 中的 Flex 并多练习以掌握它。

    在您的情况下,只需将 alignSelf: 'flex-start' 添加到 backBtnStyle StyleSheet 以使其成为您的父组件的第一个

    这里是演示代码:

    headerStyle: {
        backgroundColor: Colors.primary,
        flexDirection: 'row',
        alignItems: 'center',
        alignSelf: 'flex-start'
    },
    
    <TouchableOpacity style={styles.backBtnStyle}>
       <Image source={require('../graphics/icons/arrow_left_white.png') }/>
    </TouchableOpacity>
    

    您会看到:TouchableOpacity 包含一个可查看的布局并包装您的图像,然后您需要为 TouchableOpacity 设置样式以使 flex 工作,而不是在 Image。

    来自 React NativeTouchableOpacity 文档:不透明度是通过将子项包装在 Animated.View 中来控制的,该 Animated.View 将添加到视图层次结构中。请注意,这会影响布局。

    你可以看到Touchable Opacity Document here

    注意:在 StyleSheet.create() 上设置您的样式表,使其在您的捆绑包加载时创建一个且仅一次。它使您的应用更轻巧,速度更快

    阅读 React Native StyleSheet here

    【讨论】:

      【解决方案2】:

      您在容器中使用alignItems: 'center',因此所有内容都将位于中心。

      在您的情况下,有很多可用的解决方案。更简单的是在styles.backBtnStyle 中使用position: absolute; left: 15

      【讨论】:

        猜你喜欢
        • 2019-09-20
        • 2018-02-02
        • 2016-04-11
        • 1970-01-01
        • 2015-10-06
        • 2021-01-28
        • 1970-01-01
        • 2020-03-22
        • 1970-01-01
        相关资源
        最近更新 更多