我是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组件位于中心,但它仍保留在屏幕的左上角
答案 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 }
完整代码
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
}
});