有没有办法在本机文本周围包裹背景颜色?

时间:2019-06-30 01:19:32

标签: reactjs react-native

当前,这就是我要避免的事情。如您所见,背景颜色一直运行到宽度的尽头。最好用背景色包围文本。

enter image description here

我看了无数的示例,但我真的看不到它们在文本本身周围包裹背景颜色的地方

<Text style={{backgroundColor:'blue'}}> TTeexxtt </Text>

我尝试过flexWrap,但效果却并非如此

<Text style={{backgroundColor:'blue', flexWrap:'wrap'}}> TTeexxtt </Text>

一如既往,谢谢

1 个答案:

答案 0 :(得分:1)

two text lines with different sized pink and orange backgrounds behind them

以本机默认视图进行拉伸的alignItems属性。那是什么意思呢?

视图中的所有子项都将拉伸以填充其父项的宽度,并考虑边距。

如果您将父视图的alignItems属性设置为stretch以外的其他内容,例如centerflex-startflex-end,则会看到背景颜色仅在您的实际文本周围延伸。

您还可以在“文本”视图上使用alignSelf来调整各个项目。

这里是小吃的例子 https://snack.expo.io/@ajthyng/vengeful-celery

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';

const BGText = props => {
  const { background } = props;
  return <Text style={{backgroundColor: background, ...props.style}}>{props.children}</Text>;
}

export default class App extends React.Component {
  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'white', alignItems: 'stretch', marginTop: 23}}>
        <BGText background='pink' style={{marginRight: 16}}>I am some text</BGText>
        <BGText background='orange' style={{alignSelf: 'flex-start', marginLeft: 16}} >My BG Color is short</BGText>
      </View>
    );
  }
}
相关问题