我有以下几点

<View style={{maxWidth: 700}}>
  <View style={{backgroundColor: 'red', flexDirection: 'row', justifyContent: 'space-between'}}>
    <Text>Left Item</Text>
    <Text>Right Item</Text>
  </View>
</View>

正如我在大型设备上预期的那样(垂直黑线是模拟器屏幕的边缘).

enter image description here

我只想把它放在屏幕中央.

当我试图通过向父对象添加alignSelf:"center"来执行此操作时

<View style={{maxWidth: 700, alignSelf: 'center'}}>
  <View style={{backgroundColor: 'red', flexDirection: 'row', justifyContent: 'space-between'}}>
    <Text>Left Item</Text>
    <Text>Right Item</Text>
  </View>
</View>

宽度丢失了.

enter image description here

我认为这是因为默认情况下它是"拉伸"的.有没有一种方法既可以拉伸内容以使用maxWidth,又可以使其在屏幕上居中?

推荐答案

试着用flex:1maxWidth来拉伸,但宽度限制在700

<View style={{flexDirection:'row', alignItems: 'center', justifyContent: 'center'}}>
    <View style={{flex:1, maxWidth: 700, backgroundColor:'red', flexDirection:'row', justifyContent:'space-between'}}>
        <Text>Left Item</Text>
        <Text>Right Item</Text>
    </View>
</View>

React-native相关问答推荐

没有给出相同价值观的时刻

在第二次加载时仅将本机应用程序设置为状态

领带麦克风在Reaction-Native-Incall-Manager中不工作

expo 使用错误的版本代码创建建筑

React native + react-query + onError 不捕获并处理错误?

使用react native 杀死应用程序后蓝牙仍处于活动状态

React-Native-Web 错误:rnw_blogpost.bundle.js:1414 Uncaught TypeError: Cannot read properties of undefined (reading 'isBatchingLegacy')

如何在 React Native 的嵌套 Touchable 中传播touch 事件?

中彼此相邻对齐(Align) react native

错误:无法解析模块`buffer`

React Native:如何获取文件大小、mime 类型和扩展名?

在关闭 react-native 时更改 Switch 的 colored颜色

React Native 创建自定义组件/库

如何在 react-native 中为在后台杀死的 android 应用程序保持状态

React Native:如何将文件拆分为多个文件并导入它们?

如何在本机代码(Java、ObjectiveC/Swift)中读取 AsyncStorage

无法运行 jetifier React Native

react-native iOS 应用在部署后不显示静态/本地资源

React Native 必须双击才能使 onPress 工作

React Native 构建命令失败:PhaseScriptExecution ... (domain=NSPOSIXErrorDomain, code=2)