当尝试使用ScrollView时,它似乎不尊重其父容器的justifyContent。
import React from 'react';
import { Text, ScrollView, StyleSheet, TextStyle, View, ViewStyle } from 'react-native';
interface TODO_TextCard {
text: string,
}
export const TODO_TextCard: React.FunctionComponent<TODO_TextCard> = (props: TODO_TextCard) => {
return <View style={styles.viewStyle}>
<ScrollView>
<Text style={styles.quoteTextStyle}>{props.text}</Text>
</ScrollView>
</View>;
}
const styles = StyleSheet.create({
quoteTextStyle: {
fontSize: 30,
fontStyle: 'italic'
} as TextStyle,
viewStyle: {
flex: 1,
borderWidth: 2, borderColor: 'red',
justifyContent: 'center',
paddingHorizontal: 10
} as ViewStyle,
}); <TODO_TextCard text={'The mind adapts and converts to its own purposes the obstacle to our acting. The impediment to action advances action. What stands in the way becomes the way'}/>渲染为:

现在,如果我删除并仅呈现文本,例如
export const TODO_TextCard: React.FunctionComponent<TODO_TextCard> = (props: TODO_TextCard) => {
return <View style={styles.viewStyle}>
<Text style={styles.quoteTextStyle}>{props.text}</Text>
</View>;
}文本元素确实遵循父元素的justifyContent:center,并呈现为:

卷轴视图可以居中吗?
我现在想到的解决方案是检查文本的长度,并有条件地呈现Scroll View,如下所示:
/** This some text length would have to be different depending on the device screen, and
* even with different device screens would still not work all the time if the text
* can have new lines in it.*/
const SOME_TEXT_LENGTH = 300;
export const TODO_TextCard: React.FunctionComponent<TODO_TextCard> = (props: TODO_TextCard) => {
return <View style={styles.viewStyle}>
{props.text.length > SOME_TEXT_LENGTH ?
<ScrollView>
<Text style={styles.quoteTextStyle}>{props.text}</Text>
</ScrollView>
:
<Text style={styles.quoteTextStyle}>{props.text}</Text>
}
</View>;
}这非常不理想,因为不同的设备屏幕以及可能具有新行的文本。
发布于 2021-08-16 07:30:19
事实上,ScrollView确实尊重其父对象的justifyContent:center。ScrollView放置在外部视图组件的中心。但在这里,ScrollView占据了整个垂直屏幕,所以它看起来并不居中。
尝试设置<ScrollView style={{backgroundColor: 'green'}}>来理解我的意思。

尝试对ScrollView本身应用viewStyle或类似的样式。确保使用属性contentContainerStyle而不是style。这段代码对我来说很有效。
<View style={styles.viewStyle}>
<ScrollView contentContainerStyle={{flex: 1, justifyContent: 'center'}}>
<Text style={styles.quoteTextStyle}>{props.text}</Text>
</ScrollView>
</View>

我还找到了this的文章。也许这也能帮到你。
发布于 2021-08-16 09:38:03
您需要为ScrollView提供样式,对于样式ScrollView,您可以使用style或contentContainerStyle prop:
样式定义了ScrollView的外部容器,例如它的高度以及与兄弟元素的关系
contentContainerStyle定义了它的内部容器,例如项对齐、填充等
在您的情况下,您需要提供contentContainerStyle来定位您的项目,例如:
return (
<View style={styles.viewStyle}>
{props.text.length > SOME_TEXT_LENGTH ?
<ScrollView
contentContainerStyle={{
flex: 1, //To take full screen height
justifyContent: 'center',
alignItems: 'center,
}}>
<Text style={styles.quoteTextStyle}>{props.text}</Text>
</ScrollView>
:
<Text style={styles.quoteTextStyle}>{props.text}</Text>
}
</View>
);https://stackoverflow.com/questions/68797765
复制相似问题