Reactjs 模态弹出窗口未居中

Reactjs 模态弹出窗口未居中,reactjs,react-native,styles,Reactjs,React Native,Styles,我正在做一个简单的游戏,我想当用户输了一个模式弹出显示信息。我能够创建模式,但它不会出现在屏幕的中心,尽管它的包装视图是这样设计的。它一直出现在屏幕的左上角。我不明白这是为什么 我试着在样式表中编辑模态的位置,然后输入数字表示它的左右移动。然而,我相信这是不必要的,因为它的容器已经被设计成位于屏幕中央。此外,输入这些值会使其在不同的屏幕上显示不同 import React, { Component } from 'react'; import { Platform, Animated,

我正在做一个简单的游戏,我想当用户输了一个模式弹出显示信息。我能够创建模式,但它不会出现在屏幕的中心,尽管它的包装视图是这样设计的。它一直出现在屏幕的左上角。我不明白这是为什么

我试着在样式表中编辑模态的位置,然后输入数字表示它的左右移动。然而,我相信这是不必要的,因为它的容器已经被设计成位于屏幕中央。此外,输入这些值会使其在不同的屏幕上显示不同

import React, { Component } from 'react';
import {
  Platform,
  Animated,
  StyleSheet,
  Text,
  View,
  Button,
  Alert,
  Image,
  TouchableHighlight,
  Modal,
  TouchableOpacity,
} from 'react-native';
import { AsyncStorage } from 'react-native';
import Animater from './Animater';
import HscoreImage from './HscoreImage';


const AnimatedButton = Animated.createAnimatedComponent(TouchableHighlight);

export default class GameActivity extends Component {
  constructor(props) {
    super(props);

    // AsyncStorage.setItem('hscore', '1');
    this.state = {
      cscore: 0,
      hscore: 0,
      modalVisible: false,
    };
  }


  setModalVisible(visible) {
    this.setState({modalVisible: visible});
  }

  static navigationOptions = {
    title: "Game",
    headerStyle: {
      backgroundColor: "#73C6B6"
    }
  };


  componentDidMount() {

    this.retrieveData();

  }

  getPoints = isLost => {
    if (isLost) {
      this.setState({ cscore: 0 }, () => {
        this.updatehscore()
      });
    } else {
      this.setState({ cscore: this.state.cscore + 1 }, () => {
        this.updatehscore()
      });

      //console.log( 'hscore after retrieve'  + this.retrieveData() );
    }


  }; //end of getpoints

  updatehscore = () => {
    if (this.state.cscore > this.state.hscore) {

      // this.setState({ hscore: this.state.cscore });
      this.storeData(this.state.cscore);

    }
    this.retrieveData();
  }

  // create a function that saves your data asyncronously
  storeData = async score => {
    try {
      await AsyncStorage.setItem('hscore', score.toString());
      console.log('Saved');
      //Alert.alert('Saved')
    } catch (error) {
      // Error saving data
      console.log('Error saving score');
    }

  };

  // fetch the data back asyncronously
  retrieveData = async () => {
    try {
      const value = await AsyncStorage.getItem('hscore');
      const item = JSON.parse(value);

      if (item == null) {
        this.setState({ hscore: 0 });
      } else if (item !== null) {
        // Our data is fetched successfully
        this.setState({ hscore: item });
        console.log('IF NOT NULL: ' + parseInt(item));
        return parseInt(item);
      }
    } catch (error) {
      // Error retrieving data
      AsyncStorage.setItem('hscore', '0');
      console.log('Error getting score ' + error);
    }
  };


  render() {
    return (
      <View style={styles.mainContainer}>
        <View style = {styles.containerHscore}>
        <View style = {styles.hscoreImage}>
        <HscoreImage />
        </View>
        <Text style={styles.hscore}>
          {this.state.hscore}
        </Text>
        </View>
        <Text style={styles.score}>
          {this.state.cscore}
        </Text>
        <View style={styles.container}>
          <Animater callForPoints={this.getPoints}  currentScore = {this.state.cscore}/>


        <Modal 
          animationType="slide"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>

            <View style= {styles.modalContent}>
              <Text>Hello World!</Text>

              <TouchableHighlight
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
                <Text>Hide Modal</Text> 
              </TouchableHighlight>
            </View>

        </Modal>

        <TouchableHighlight
          onPress={() => {
            this.setModalVisible(true);
          }}>
          <Text>Show Modal</Text>
        </TouchableHighlight>
       </View>
     </View>

      //<PresentationalComponent color = {[animatedStyle]} showAlert = {this.showAlert}/>
    );
  }
}

const styles = StyleSheet.create({
  mainContainer: {
    // display: flex,
    flex: 1,
    backgroundColor: '#00c4cc',
  },
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
  score: {
    position: 'absolute',
    textAlign: 'center',
    fontSize: 175,
    justifyContent: 'center',
    alignItems: 'center',
    top: 45,
  },
  hscore: {
    textAlign: 'right',
    fontSize: 40,
    justifyContent: 'center',
    alignItems: 'center',
    top: 50,
  },
  hscoreImage: {
    alignSelf:'flex-end',
    justifyContent: 'center',
    alignItems: 'center',
    top: 50,
  },
  containerHscore: {
    flexDirection: 'row',
    alignSelf:'flex-end',

  },
  modalContent: {
    backgroundColor: 'white',
    padding: 22,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 100,
    width: 20,
    height: 20,
    borderColor: 'rgba(0, 0, 0, 0.1)',
  },
});
import React,{Component}来自'React';
进口{
平台,
有生气的
样式表,
文本,
看法
按钮
警觉的,
形象,,
触控高光,
情态动词
可触摸不透明度,
}从“反应本机”;
从“react native”导入{AsyncStorage};
从“./Animater”导入动画师;
从“/HscoreImage”导入HscoreImage;
const AnimatedButton=Animated.createAnimatedComponent(TouchableHighlight);
导出默认类GameActivity扩展组件{
建造师(道具){
超级(道具);
//AsyncStorage.setItem('hscore','1');
此.state={
cscore:0,
hscore:0,
modalVisible:错误,
};
}
setModalVisible(可见){
this.setState({modalVisible:visible});
}
静态导航选项={
标题:“游戏”,
头型:{
背景颜色:“73C6B6”
}
};
componentDidMount(){
这个。retrieveData();
}
getPoints=isLost=>{
如果(isLost){
this.setState({cscore:0},()=>{
this.updatehscore()
});
}否则{
this.setState({cscore:this.state.cscore+1},()=>{
this.updatehscore()
});
//log('hscore after retrieve'+this.retrieveData());
}
};//getpoints的结尾
更新分数=()=>{
if(this.state.cscore>this.state.hscore){
//this.setState({hscore:this.state.cscore});
this.storeData(this.state.cscore);
}
这个。retrieveData();
}
//创建一个异步保存数据的函数
storeData=异步分数=>{
试一试{
等待AsyncStorage.setItem('hscore',score.toString());
console.log('Saved');
//Alert.Alert('已保存')
}捕获(错误){
//保存数据时出错
console.log('Error saving score');
}
};
//异步取回数据
retrieveData=async()=>{
试一试{
const value=await AsyncStorage.getItem('hscore');
const item=JSON.parse(值);
如果(项==null){
this.setState({hscore:0});
}else if(项!==null){
//我们的数据已成功获取
this.setState({hscore:item});
log('IF NOT NULL:'+parseInt(item));
返回parseInt(项目);
}
}捕获(错误){
//检索数据时出错
AsyncStorage.setItem('hscore','0');
log('Error get score'+Error);
}
};
render(){
返回(
{this.state.hscore}
{this.state.cscore}
{
警报。警报('模式已关闭');
}}>
你好,世界!
{
this.setModalVisible(!this.state.modalVisible);
}}>
隐藏模态
{
此.setModalVisible(true);
}}>
显示模态
//
);
}
}
const styles=StyleSheet.create({
主容器:{
//显示:flex,
弹性:1,
背景颜色:“#00c4cc”,
},
容器:{
位置:'绝对',
排名:0,
左:0,,
右:0,,
底部:0,
为内容辩护:“中心”,
对齐项目:“居中”,
},
分数:{
位置:'绝对',
textAlign:'中心',
尺寸:175,
为内容辩护:“中心”,
对齐项目:“居中”,
前45名,
},
hscore:{
textAlign:'右',
尺寸:40,
为内容辩护:“中心”,
对齐项目:“居中”,
前50名,
},
hscoreImage:{
alignSelf:“柔性端”,
为内容辩护:“中心”,
对齐项目:“居中”,
前50名,
},
容器分数:{
flexDirection:'行',
alignSelf:“柔性端”,
},
模块内容:{
背景颜色:“白色”,
填充:22,
为内容辩护:“中心”,
对齐项目:“居中”,
边界半径:100,
宽度:20,
身高:20,
边框颜色:“rgba(0,0,0,0.1)”,
},
});

我希望模态显示在屏幕中央,但它没有显示。

首先在模态内部使用

flex: 1,
alignItems: 'center',
justifyContent: 'center'
然后你的中心内容

比如说

<Modal>
    <View
        style = {{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center'
        }}
    >
        //All view here will be centered, replace below view with your own
        <View
           style = {{
               backgroundColor: 'red',
               height: 20,
               width: 20
           }}
        />
    </View>
</Modal>

//这里的所有视图都将居中,用您自己的视图替换下面的视图

这很有效,谢谢。你能解释一下为什么要这么做吗。我很难理解如何在React-Nativeyour welcome@Gintak27中正确设置样式,因为alignItems是对齐内部项目而不是自身视图,与justifyContent相同。因此,基本上从我的示例中,我创建了全宽和全高透明视图,然后使用alignItems和justifyContent将视图中的所有视图居中。如果您发现此答案可以解决您的问题,请标记此答案:)