我试图在给出一定数量的文本的反应原生中产生效果,它包装并同时垂直增加大小,为下一个单词创建一个新行:
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
const styles = StyleSheet.create({
container: {
flex: 0.3,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
alignSelf: 'center',
},
wordsContent: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap'
},
txt: {
flex: 1,
flexDirection: 'row',
alignSelf: 'center',
width
}
});
export default class App extends Component<Props> {
render() {
const words = ['asdfasdf', 'asdf asdf', 'qwerqwer', 'qwer qwer', 'qwerwwe', 's332', '123123', 'sdfasdf'];
return (
<View style={styles.container}>
<View style={styles.wordsContent}>
<Text style={styles.welcome}>
Words:
</Text>
{
words.map((w, i) =>
<Text style={styles.txt} key={i}>
{w}
</Text>
)
}
</View>
</View>
);
}
}
我想继续在数组中添加单词,这些单词应该转到下一行。请注意,数组中的“单词”可以包含空格。
答案 0 :(得分:0)
我最终做了一个不优雅的解决方案:
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
flex: 1,
alignSelf: 'center',
},
wordsWrapper: {
flex: 1,
flexDirection: 'row'
},
wordsContent: {
flex: 0.5,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
flexWrap: 'wrap',
},
word: {
alignSelf: 'center',
paddingLeft: 5,
paddingRight: 5
},
txt: {
paddingLeft: 5,
paddingRight: 5,
borderWidth: 0.5,
justifyContent: 'center',
borderColor: 'black',
}
});
export default class App extends Component<Props> {
getWordsPerColumn() {
const words = ['asdfasdf', 'asdf asdf', 'qwerqwer', '123321', 'asdfasdf', 'asdf asdf', 'qwerqwer', '123321', 'asdf asdf', 'qwerqwer', '123321', 'asdf asdf', 'qwerqwer', '123321', 'qwerqwer', '123321' ];
const maxColumns = 5;
const cells = 4;
let columns = maxColumns;
if (words.length <= 4) {
columns = 1;
} else if (words.length <= 8) {
columns = 2;
} else if (words.length <= 12) {
columns = 3;
} else if (words.length <= 16) {
columns = 4;
}
const groups = [];
let groupNumber = 0;
let keys = 0;
for(let i = 1; i <= columns; i++) {
if (!groups[groupNumber]) {
groups.push([]);
}
for(let j = 1; j <= cells; j++) {
groups[groupNumber].push(
<Text key={keys} style={styles.word}>
{
words[keys]
}
</Text>
);
keys++;
}
groupNumber++;
}
return groups;
}
render() {
let key = 0;
return (
<View style={styles.container}>
<View style={styles.wordsContent}>
<Text style={styles.welcome}>
Words:
</Text>
<View style={styles.wordsWrapper}>
{
this.getWordsPerColumn().map((column, i) => (
<View key={key++} style={styles.txt} >
{
column.map((w, j) => w)
}
</View>
)
)
}
</View>
</View>
</View>
);
}
}
目前我预计不会有超过一定数量的词语......在不久的将来,我可能需要一个比这更好的解决方案,欢迎任何好主意。