简体   繁体   中英

React Native place a text over SVG image

I'm using libraries: "react-native-svg": "12.1.0" & "react-native-svg-transformer": "0.14.3"

import FooIcon from '../assets/images/icons/fooIcon.svg';

<View style={{ flex: 1, paddingTop: 8 }}>
   <FooIcon></FooIcon>
   <View style={{ position: 'absolute', top: 35, bottom: 0, left: 14, right: 0 }} >
      <Text>foo</Text>
   </View>
</View>

How can I have "foo" text centered over the FooIcon. The solution above does not center the text which is important because "foo" text length can change and it has to be in center in every case.

在此处输入图像描述

this chunk of code should do the work for you

    <View
    style={{
      justifyContent: 'center',
      alignItems: 'center'
    }}
    >
    <SVG /> //your svg image component goes here
    <Text
      style={{
        position: 'absolute'
      }}
    >
      Test
    </Text>
  </View>

I would recommend not to use an absolute position if the content size can change dynamically. I would build this with just using flex-box:

...
<View style={styles.itemContainer}>
  <Text>Foo</Text>
  <View style={styles.iconMock} />
</View>
...
const styles = StyleSheet.create({
  itemContainer: {
    alignItems: "center",
    //this has default flex: 0, which means the container will always have the size the children take.
    //we then tell it to centre all the children (items) which gives the needed effect.
  },
  iconMock: {
    backgroundColor: "blue",
    height: 50,
    width: 150,
  }
});

Building it this way the text will always be centred: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM