水平和垂直居中按钮

时间:2019-08-17 02:12:48

标签: reactjs react-native

我是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,

    },
});

我希望Animater组件位于中心,但它仍保留在屏幕的左上角

2 个答案:

答案 0 :(得分:0)

您的风格应该是

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

注意:在使用flex时,我们不需要position属性。

答案 1 :(得分:0)

要将项目与居中位置对齐:“绝对”,您必须添加以下样式

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

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

{ flex: 1 }

enter image description here

完整代码

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
  }
});