【问题标题】:ReactNative: How to have 2nd Text components share the line of 1 Text component spill overReact Native:如何让 2nd Text 组件共享 1 Text 组件溢出的行
【发布时间】:2020-09-02 17:41:30
【问题描述】:

在 React Native 中,第二个组件是否可以使用第一个文本组件溢出的部分使用的空间?

示例代码:

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

export const TextProto = () => {

    return <View>

        <Text style={{borderWidth: 2, borderColor: 'green'}}>{'str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1 str-1'}</Text>
        <Text style={{borderWidth: 2, borderColor: 'green'}}>{'str-2 str-2'}</Text>
    </View>
};

呈现为:

是否可以将其呈现为(最好通过样式设置):

【问题讨论】:

  • 为什么不只用一个和'\n'来换到下一行呢?
  • 您可以使用文本组件更改外部视图,这样您就可以获得您想要的。但是边框不适用于文本组件内部的文本组件。 (你可以在这里看到github.com/facebook/react-native/issues/10775)但是你可以使用这个糟糕的解决方法github.com/facebook/react-native/issues/…
  • @JoseCabreraZuniga 我猜 op 希望它具有响应性并且感觉像内联 css 显示

标签: reactjs react-native react-native-android


【解决方案1】:

作为 @Uğur Eren stated,边框不适用于文本组件,但您可以通过为字符串或字符串集中的每个单词使用不同的背景颜色来实现类似的效果。

以下是您案例的简单实现:

import React from "react";
import "./styles.css";
import { View, Text, StyleSheet } from "react-native";


const sentences = [
  {
    backgroundColor: "#cfa",
    color: "#000",
    sentence: "This is my first line that is very very long"
  },
  {
    backgroundColor: "#edf",
    color: "#000",
    sentence: "There it is a second one"
  },
  { backgroundColor: "#ecd", color: "#000", sentence: "Lorem ipsum veliyedin" }
];

export default function App() {
  return (
    <View style={styles.container}>
      {sentences.map(({ color, backgroundColor, sentence }) => {
        return sentence.split(" ").map((word) => {
          return (
            <Text style={[styles.text, { color, backgroundColor }]}>
              {word}
            </Text>
          );
        });
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexWrap: "wrap",
    flexDirection: "row",
    alignSelf: "flex-start"
  },
  sentence: {
    flexWrap: "wrap",
    flexDirection: "row",
    alignSelf: "flex-start"
  },
  text: {
    padding: 5,
    backgroundColor: "#eee"
    // margin:5
  }
});

CodeSandbox

【讨论】:

    猜你喜欢
    • 2016-11-18
    • 2018-08-18
    • 2020-05-06
    • 1970-01-01
    • 2021-08-17
    • 2017-12-30
    • 1970-01-01
    • 2023-03-21
    • 2015-12-04
    相关资源
    最近更新 更多