将图像居中在React Native组件中

时间:2018-07-04 06:57:32

标签: react-native

我已经开始使用React Native,并且我试图创建一个简单的图像按钮组件以适应该语言。 这是我所拥有的:

'use strict';

const React = require('React');
const PropTypes = require('prop-types');

import {
    Platform, TouchableOpacity,
    StyleSheet, Dimensions,
    Text, Image,
    View
  } from 'react-native';
const TouchableNativeFeedback = require('TouchableNativeFeedback');


const MyBrown = '#89664C';
const styles = StyleSheet.create({
    button: Platform.select({
        ios: {
        },
        android: {
            elevation: 4,
            backgroundColor: MyBrown,
            borderRadius: 2
        }
    }),
    text: Platform.select({
        ios: {
            color: 'white',
            textAlign: 'center',
            padding: 8,
            fontSize: 18
        },
        android: {
            color: 'white',
            textAlign: 'center',
            padding: 8,
            fontWeight: '500',
        }
    }),
    icon: {
        width: 60,
        height: 60,
    }
});

export default class MyButton extends React.Component{

    render(){            
        return(
            <View style={styles.button}>
                <TouchableOpacity>                    
                    <Image source={this.props.src} style={styles.icon} />
                    <Text style={styles.text}>{this.props.text}</Text>
                </TouchableOpacity>
            </View>
            )
    }
}

这将按照我在运行应用程序时的预期进行渲染,但是图像居中对齐,而文本居中。 现在,我想可以使用Flexbox并将 {flex:1} 添加到父级View或TouchOpacity元素中,但是一旦执行此操作,控件便不再在我的应用程序中呈现。

对此有两个问题:

  1. 在React中将图像居中的推荐方法是什么 本地人?
  2. 为什么,当我将flex:1添加到父级的ether中时 控件完全不再呈现?

谢谢

1 个答案:

答案 0 :(得分:0)

基本上,使图像居中的最佳方法是将其与父视图一起包装并为其添加弹性样式,而无需通过flex: 1

> justifyContent: 'center',
> alignItems: 'center',
  1. 照顾图像大小的首选方法是宽度和高度,弯曲度:1,应用于背景图像等