簡體   English   中英

有沒有辦法在 react-native 中將背景顏色包裹在文本周圍?

[英]Is there a way to wrap background color around text in react-native?

目前,這是我試圖避免的。 如您所見,背景顏色一直持續到寬度的末尾。 背景顏色環繞文本會很好。

在此處輸入圖片說明

我查看了大量示例,但我真的沒有看到它們在文本本身周圍環繞背景顏色的位置

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

我嘗試過 flexWrap 但它不像這樣工作

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

一如既往,謝謝

兩個文本行,后面有不同大小的粉紅色和橙色背景

視圖中的本機默認為拉伸的alignItems道具。 但這意味着什么?

考慮到邊距,您視圖的所有子項都將拉伸以填充其父項的寬度。

如果您將父視圖的alignItems屬性設置為stretch其他內容,例如centerflex-startflex-end您將看到背景顏色僅圍繞您的實際文本延伸。

您還可以在 Text 視圖上使用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>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM