在 React Native 组件中居中图像

she*_*per 4 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>
            )
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,这会按照我的预期呈现,但是图像左对齐,而文本居中。现在我想我可以使用 Flexbox 并将{flex:1}添加到父 View 或 TouchOpacity 元素,但是一旦我这样做,控件就不再在我的应用程序中呈现。

关于这个的两个问题:

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

谢谢

Woj*_*iec 5

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

> justifyContent: 'center',
> alignItems: 'center',
Run Code Online (Sandbox Code Playgroud)
  1. 处理图像大小的首选方法是宽度和高度,flex: 1 您应该用于背景图像等

  • 我建议在“TouchableOpacity”中添加“View”,并将样式传递给该视图 (2认同)