React Native文本溢出屏幕,拒绝自动换行。该怎么办?

312
以下代码可以在这个实例中找到。
我有以下的React Native元素:
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var SampleApp = React.createClass({
  render: function() {
    return      (
  <View style={styles.container}>

        <View style={styles.descriptionContainerVer}>
          <View style={styles.descriptionContainerHor}>
            <Text style={styles.descriptionText} numberOfLines={5} >
              Here is a really long text that you can do nothing about, its gonna be long wether you like it or not, so be prepared for it to go off screen. Right? Right..!
            </Text>
          </View>
        </View>

        <View style={styles.descriptionContainerVer2}>
          <View style={styles.descriptionContainerHor}>
            <Text style={styles.descriptionText} numberOfLines={5} >Some other long text which you can still do nothing about.. Off the screen we go then.</Text>
          </View>
        </View>



  </View>);
  }
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);

带有以下样式:
var styles = StyleSheet.create({
  container:{
        flex:1,
    flexDirection:'column',
        justifyContent: 'flex-start',
        backgroundColor: 'grey'
    },
    descriptionContainerVer:{
    flex:0.5, //height (according to its parent)
    flexDirection: 'column', //its children will be in a row
    alignItems: 'center',
    backgroundColor: 'blue',
    // alignSelf: 'center',
  },
  descriptionContainerVer2:{
    flex:0.5, //height (according to its parent)
    flexDirection: 'column', //its children will be in a row
    alignItems: 'center',
    backgroundColor: 'orange',
    // alignSelf: 'center',
  },
  descriptionContainerHor:{
    //width: 200, //I DON\'T want this line here, because I need to support many screen sizes
    flex: 0.3,  //width (according to its parent)
    flexDirection: 'column',    //its children will be in a column
    alignItems: 'center', //align items according to this parent (like setting self align on each item)
    justifyContent: 'center',
    flexWrap: 'wrap'
  },
  descriptionText: {
    backgroundColor: 'green',//Colors.transparentColor,
    fontSize: 16,
    color: 'white',
    textAlign: 'center',
    flexWrap: 'wrap'
  }
});

这将导致以下屏幕显示:

Text off screen app

如何避免文本超出屏幕并将其限制在屏幕中央,宽度为父元素的80%。

我认为不应该使用width,因为我将在许多不同的移动屏幕上运行它,并且希望它是动态的,因此我认为应完全依赖于flexbox

(这就是为什么我在descriptionContainerHor中使用了flex:0.8的初始原因。

我想要实现的效果类似于这样:

What I want to achieve

谢谢!

25个回答

8

我尝试了上面提供的许多答案,但都不适用于我。我通过在

我需要在父级上使用flexDirection: row,因为我想在右侧放置一个图标。

<View style={flexDirection: 'row', flexGrow: 1}>
    <Text style={
        flexGrow: 1, 
        flexShrink: 1, 
        paddingLeft: 16,
        paddingRight: 8,
        alignItems: 'center',
    }>
        A long text that needs to wrap into multiple lines
    </Text>
</View>
<Image source={rightArrow}/>

它看起来像这样:

文本自动换行成多行的屏幕截图


3

我想补充一下,我也遇到了同样的问题,无论是flexWrap、flex:1(在文本组件中),还是其他任何flex属性都没有起作用。

最终,我将文本组件包装器的宽度设置为设备的宽度,文本就开始自动换行了。 const win = Dimensions.get('window');

<View style={{
  flex: 1,
  flexDirection: 'column',
  justifyContent: 'center',
  alignSelf: 'center',
  width: win.width
}}>
  <Text style={{ top: 0, alignSelf: 'center' }} >{image.title}</Text>
  <Text style={{ alignSelf: 'center' }}>{image.description}</Text>
</View>

3
在React Native版本0.62.2中,我在我的“Text”容器中的“Container”中只是加了“flex-shrink:1”,但请记住容器的“View”中的“flex-direction:row”。谢谢大家的帮助。
我的代码:
export const Product = styled.View`
  background: #fff;
  padding: 15px 10px;
  border-radius: 5px;
  margin: 5px;
  flex-direction: row;
`;

export const ProductTitleContainer = styled.View`
  font-size: 16px;
  margin-left: 5px;
  flex-shrink: 1;
`;

export const ProductTitle = styled.Text`
  font-size: 16px;
  flex-wrap: wrap;
`;
`;

2
我认为你可以做类似于这样的事情,我已经附上了一张带有代码的图片以便更好地理解: enter image description here 因此,我们可以做如下操作:
TermsOfService = {
  fontFamily: 'Verlag-Book';
  fontSize: 14px;
  textAlign: center;
},
HighlightedText = {
  font-family: 'Verlag-Book';
  font-size: 14px;
  text-align: center;
  color: ${COLORS.PRIMARY_ADMIRAL_BLUE};
},
Container: {
  width: 100%;
  alignSelf: center;
  alignItems: center;
  justifyContent: center;
  flexDirection: row;
  flexWrap: wrap;
}

您只需像这样使用您的组件:
 <View style={Container}>
   <Text style={TermsOfService}>By joining, you agree to the some thing </Text>
   <Text style={HighlightedText}>this is highlighted </Text>
   <Text style={TermsOfService}>and </Text>
   <Text style={HighlightedText}>and this as well</Text>
 </View>

1

很不幸以上方法都对我无效。

我发现了这个npm包,你可以直接使用: https://github.com/Bang9/react-native-wrapped-text

或者创建类似于这样的东西:

<View style={{ alignItems: "center", alignSelf: "center", width: "100%" }}>
  <View style={{ flexDirection: "row", flexWrap: "wrap"}}>
    <Text style={{ textAlign: "center"}}>Long text, sooo looong...</Text>
  </View>
</View>

基于: https://github.com/Bang9/react-native-wrapped-text/blob/master/src/index.js

(该链接指向 GitHub 上 Bang9 的 react-native-wrapped-text 库的源代码)

1
尝试了一切,但没有用,只有这个可以 ->
wrapText:{
    width:"65%"
},
listItemLeft:{
    fontWeight:"bold",
    margin:3
},

<View style={styles.wrapText}>
    <Text style={styles.listItemLeft}>{item.left}</Text>
</View>

1
在文本样式中使用 height: 'auto'。

enter image description here enter image description here


1
<View style={{flexDirection:'row'}}> 
   <Text style={{ flex: number }}> You miss fdddddd dddddddd 
     You miss fdd
   </Text>
</View>

{ flex: aNumber }就是你所需要的!

只需将'flex'设置为适合您的数字。然后文本就会自动换行。


奇怪的是,这确实是对我有效的修复方法。 - Dror Bar

1

对我来说,所有的答案都不起作用,所以我决定使用一个技巧,即通过空格分割文本,并单独渲染每个单词。

虽然这是一种技巧,但好处是我不必太担心由于父容器样式而弄乱包装。

// This code is written in Typescript
import React from 'react'
import { StyleSheet, View, Text } from 'react-native'
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'center',
    paddingVertical: 8,
  },
})

export const WrapText: React.FC<{
  text: string
}> = ({ text }) => {
  return (
    <View style={styles.container}>
      {text.split(' ').map((word, index) => (
          <Text key={index}>
            {word}{' '}
          </Text>
        ))}
    </View>
  )
}

const Example = <WrapText text="Hello this is a working hack that wraps your text."/>

P/S:当然,这仅适用于字母书写系统,其他不使用空格的书写系统(例如中文书写)将不会使用此组件进行换行。


0
<SafeAreaView style={{flex:1}}>
  <View style={{alignItems:'center'}}>
    <Text style={{ textAlign:'center' }}>
      This code will make your text centered even when there is a line-break
    </Text>
  </View>
</SafeAreaView>

2
请注释您的代码并解释您的答案。 - phoenixstudio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接