【问题标题】:React Native: Image doesn’t vetrically align center in nested textReact Native:图像在嵌套文本中没有垂直对齐中心
【发布时间】:2021-09-23 19:45:57
【问题描述】:

问题陈述

我需要在一个段落中嵌套多个图像。如果它是单行文本,我会用 flexDirection: 'row' 包裹 <View>。由于这不能解决用例,我用 <Text> 包装了所有文本和图像。

图片供参考

按照我目前的方法,图像会嵌套,但不会与文本居中对齐。我尝试了一些修复,您可以在 styles.fix

下查看

在每个突出显示的部分中,信封图像与文本的基线对齐,但它必须在每个突出显示的红色框内垂直对齐中心

代码

import React from 'react';
import { Text, View, SafeAreaView, StyleSheet, Image } from 'react-native';

import Img from './img.png';

export default () => {
  return (
    <SafeAreaView style={styles.rootContainer}>
      <View style={styles.container}>
        <Text>
          <Text>This is a long paragraph with icon here </Text>
          <Image style={[styles.img, styles.fix]} source={Img} />
          <Text> on the next line as well </Text>
          <Image style={[styles.img, styles.fix]} source={Img} />
          <Text> and and and and and here too </Text>
          <Image style={[styles.img, styles.fix]} source={Img} />
          <Text> but the icons are not center aligned with the text.</Text>
        </Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  rootContainer: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    margin: 20,
    padding: 20,
    borderWidth: 1,
    borderRadius: 5,
  },
  img: {
    width: 23,
    height: 15,
  },
  fix: {
    /**
     * `tried lowering position with relative positioning but didn't work`
     * top: 10,
     * position: 'relative',
     *
     * `margin didn't work either as it messed up icon proportions`
     * marginTop: 10,
     *
     * also tried wrapping Image in a View with
     * marginTop or relative positioning but the
     * results were same as the above two
     */
  },
});

【问题讨论】:

    标签: javascript css reactjs image react-native


    【解决方案1】:

    你检查了吗? React - vertically align text and icon

    我没有看到在这里使用 align-items 和 flex。尝试使用 alignItems: "center" 包裹在 View 中,使其垂直对齐。

    【讨论】:

    • 不,我不会检查,因为这是一个 React 问题。任何答案都不会解决我的用例。而alignItems: "center" 将不起作用,因为它只能对齐根&lt;Text&gt; 而不是它的孩子&lt;Text&gt;&lt;Image&gt;
    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多