将填充设置为嵌套的 React Native Text 组件在 Android 中不起作用

ton*_*on1 7 react-native

我想要的是将填充设置为嵌套<Text>在React Native中,它在基于Web的react-native中工作,但Android设备或模拟器无法正常工作。以下是我想要的。

在此输入图像描述


但是,就像下面的截图一样,在 Android 设备或模拟器中,您可以看到info的填充不受影响。我该如何做到这一点?

在此输入图像描述


https://snack.expo.io/HJBd!h2l8

代码很简单。

 <Text>
   <Text style={{ padding: 10, backgroundColor: "yellow"}}>Info</Text> What I want to is simple.
 </Text>
Run Code Online (Sandbox Code Playgroud)

Yun*_*hai 8

由于<Text>不支持在react-native中填充组件内部,因此您想要的方法有点棘手,并且可能会导致一些不需要的布局。您可以使用以下示例代码来查看这种方法的问题,而无需使用诸如传递 Props 或创建自己的组件等复杂的方式。

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

export default class App extends React.Component {
  render() {
    return (
      <View style={{flexDirection: "column", paddingTop:50}}>
        <View style={{flexDirection:'row', flexWrap: 'wrap'}}>
          <Text style={{ padding:10, fontSize: 11, backgroundColor: "yellow"}}>Info</Text>
          <Text style={{paddingTop:10}}>This line need to set padding too</Text>
          <Text>Below long long long long long long long long text</Text>
        </View>

        <View style={{paddingTop: 20, flexDirection:'row', flexWrap: 'wrap'}}>
          <Text style={{ padding:10, fontSize: 11, backgroundColor: "yellow"}}>Info</Text>
          <Text style={{paddingTop:10}}>what happen if the line is too long long long long long long long </Text>
          <Text>Below long long long long long long long long text</Text>
        </View>
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

更新:肮脏和糟糕的方式。使用lineHeight就是模拟padding top and bottom,添加whitespace就是创造padding left and right

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

export default class App extends React.Component {
  render() {
    return (
      <View style={{ paddingTop: 60 }}>

      <Text>
      <Text style={ style.TextHightlight }>    Info    </Text> What I want to is simple. if longlon g longlong longlongl  onglonglong longlonglonglo nglonglonglonglongl ongtext
       </Text> 

      </View>
    );
  }
}

const style = StyleSheet.create({
    TextHightlight: {
    fontSize:11,
    lineHeight: 11+11+10,
    backgroundColor: 'yellow'
  },
});
Run Code Online (Sandbox Code Playgroud)

这是一个静态示例。

对于动态字体大小。你想要创建类似的东西const DYN_FSIZE = 10;然后fontSize: DYN_FONTSIZElineHeight: DYN_FSIZE*3

同样的想法适用于空白,创建您自己的addWhiteSpace函数。