首页 > 解决方案 > 视图中的中心元素

问题描述

我有一个带有一些 TextInput 子组件的表单组件,如下所示:

const FormComponent = () => {
  return (
    <View style={StyleSheet.container}>
      <TextInput1/>
      <TextInput2/>
      <TextInput3/>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});

当我尝试使用 StyleSheet 居中对齐表单组件时,似乎什么也没发生。即,文本输入保留在屏幕的左上角。

但是,如果我将样式直接应用于视图,如下所示:

<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>

然后 textinput 组件在屏幕上居中对齐。

我不明白为什么会发生这种情况,如果可能的话,我想通过使用样式表来保持代码干净。

标签: cssreact-native

解决方案


使用样式而不是 StyleSheet ,这是一个错字

 <View style={styles.container}>
      <TextInput1/>
      <TextInput2/>
      <TextInput3/>
    </View>

推荐阅读