首页 > 解决方案 > 怎么做标签的行为类似于 react-native 中的 HTML 内联元素

问题描述

我有这个简单的 UI 结构:

<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>

  <Text>A simple fee equal to</Text>
  <View style={{ width: 80 }}>
    <TextInput style={{ borderWidth: 1, borderColor: 'black' }} />
  </View>
  <Text>of any settlement or judgment</Text>

</View>

在一个小屏幕上,它会显示这样的东西

在此处输入图像描述

如上图所示,我预计文本 ,of any settlement or judgment不会移动到下一行。

我能想到的最接近的解决方案是将每个文本分成单独的Text元素。

<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>

  <Text>A simple fee equal to</Text>
  <View style={{ width: 80 }}>
    <TextInput style={{ borderWidth: 1, borderColor: 'black' }} />
  </View>

  {'of any settlement or judgment'.split(' ').map((chunk, i) => (
    <Text key={i.toString()}>{chunk} </Text>
  )}

</View>

结果是这样的:

在此处输入图像描述

问题:有没有更好的方法来实现我想要的?或者这是解决问题的唯一方法?

标签: reactjsreact-native

解决方案


好吧,您可以将其写入具有 flexDirection:'row' 样式属性的视图中,也可以将其包装在另一个 Text 中,如下所示:

<Text>
 <Text>A simple fee equal to</Text>
  <View style={{ width: 80 }}>
    <TextInput style={{ borderWidth: 1, borderColor: 'black' }} />
  </View>
  <Text>Of any settlement or Judgement</Text>
</Text> 

推荐阅读