下面的代码可以在这个活生生的例子中找到
我有以下反应原生元素:
'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' } });
这将导致以下屏幕:
如何阻止文本离开屏幕并将其限制在屏幕中间,宽度为父级的 80%。
我认为我不应该使用它width,因为我将在许多不同的移动屏幕上运行它并且我希望它是动态的,所以我认为我应该完全依赖flexbox.
width
flexbox
(这是我flex: 0.8在descriptionContainerHor.
flex: 0.8
descriptionContainerHor
我想要实现的是这样的:
谢谢!
该问题的解决方案是flexShrink: 1.
flexShrink: 1
<View style={{ flexDirection: 'row' }} > <Text style={{ flexShrink: 1 }}> Really really long text... </Text> </View>
根据您的设置,您可能还需要添加flexShrink: 1到<View>‘s 父级,以使其正常工作,所以玩它,你会成功的。
<View>
Adam Pietrasiak在此线程中发现了解决方案。