React Native 水平和垂直居中按钮

xriantvc  于 2022-12-14  发布在  React
关注(0)|答案(3)|浏览(273)

我是React Native的新手,我正在尝试将我创建的组件垂直和水平居中。如果我将中心样式代码放在整体视图中,它会工作,但这样会使app.js中的所有内容也居中。应该有一种方法只将我创建的组件居中。
我已经尝试更改flex和diff flexbox选项。

import React, { Component } from 'react';
import {
    Platform,
    Animated,
    StyleSheet,
    Text,
    View,
    Button,
    Alert,
    TouchableHighlight,
} from 'react-native';
import Animater from './components/Animater';
import PresentationalComponent from './components/PresentationalComponent';

const AnimatedButton = Animated.createAnimatedComponent(TouchableHighlight);

export default class HelloWorldApp extends Component {

    constructor(props) {
        super(props);
        this.state = {
            listDataFromChild: null
        };
    }

    myCallback = (dataFromChild) => {
        this.setState({ listDataFromChild: dataFromChild });
    }

    render() {

      return (
        <View >     
          <Text style={styles.score}>
            Score: {this.state.listDataFromChild}
          </Text>
          <View style={styles.container}>
            <Animater  callbackFromParent={this.myCallback}/>     
          </View>
        </View>
        //<PresentationalComponent color = {[animatedStyle]} showAlert = {this.showAlert}/>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        position: 'absolute',
        paddingHorizontal: 10,

    },
    score: {
        fontSize: 30,
        alignItems: 'center',
        top: 100,

    },
});

我希望动画组件位于中间,但它仍然位于屏幕的左上角

sqougxex

sqougxex1#

将项目居中对齐位置:'absolute'您必须添加以下样式

{
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: "center",
    alignItems: "center"
  }

还请使用flex:1制作主容器

{ flex: 1 }

完整代码

import React from "react";
import { View, Text, StyleSheet } from "react-native";

export default class Home1 extends React.Component {
  render() {
    return (
      <View style={styles.mainContainer}>
        <Text style={styles.score}>Score: 50</Text>
        <View style={styles.container}>
          <Text>Animator container</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  mainContainer: { flex: 1 },
  container: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: "center",
    alignItems: "center"
  },
  score: {
    fontSize: 30,
    alignItems: "center",
    top: 100
  }
});
u1ehiz5o

u1ehiz5o2#

你的风格应该是,

container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
}

**注意:**使用flex时,不需要position属性.

41zrol4v

41zrol4v3#

我将与您分享如何在react native中将按钮水平居中。

.test1 {
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},

相关问题