ReactJS Flex布局问题

问题描述

我是新来的反应者,试图在react.js中创建一个登录表单,我搜索了一些技巧,以了解如何在.css文件中使用以下代码来居中组件和结果:

display: flex;
justify-content: center;
align-items: center;

但是,当我将上面的代码与另一个组件(窗体)中的两个组件(按钮和明文)一起使用时,应用程序会告诉我这两个组件在同一行上。我希望明文出现在按钮下方。

Image of 2 components on the same line

这是我的代码

SignIn.js

import React,{ Component } from 'react';
import './SignIn.css'

class SignIn extends Component {
    render() {
        return (
            <div className="base-container">
                <div className="form">
                    <button className="sign-in-button" type="submit">
                        Sign In With Github
                    </button>
                    <div className="copyright">
                        copyright © William Ji 2020
                </div>
                </div>
            </div>
        );
    }
}

export default SignIn;

SignIn.css

.base-container {
    font-family: Verdana,Geneva,Tahoma,sans-serif;
    justify-content: center;
    align-items: center;
    text-align: center;
    display: flex;
}

.form {
    width: 30vw;
    height: 40vh;
    background-color: whitesmoke;
    text-align: center;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    border-width: 1px;
    display: flex;
}ß

.sign-in-button {
    padding: 20px;
    text-align: center;
    justify-content: center;
    align-items: center;
}

.copyright {
    color: rgba(0,0.8);
    font-size: small;
}

App.js

import React,{Component} from 'react';
import {browserRouter as Router,Route} from 'react-router-dom';
import * as firebase from 'firebase';
import SignIn from './Components/Auth/SignIn';
import './App.css';

class App extends Component{
  render(){
    return(
      <div className="App">
        <SignIn />
      </div>
    )
  }
}

export default App;

解决方法

您可以通过添加容器样式 flex-wrap:wrap; 来解决此问题,还可以将其中的两个元素(按钮分别用div +纯文本包装)设置为宽度:100%

,

版权应该是p标签,而不是div,只是进行更改可能会将其压低。如果没有,请确保它具有display:block;并且容器具有flex-wrap:wrap;

,

您需要在父元素中使用flex-direction: column;。使用display: flex;时,默认值为flex-direction: row;

#parent-with-flex-direction-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 100px;
  width: 100px;
  margin: auto;
}

#parent-with-flex-direction-column {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  width: 100px;
  margin: auto;
}

.child {
  height: 2rem;
  width: 2rem;
  margin: 5px;
  background-color: blue;
}
<div id='parent-with-flex-direction-row'>
  <div class='child'>
  </div>
  <div class='child'>
  </div>
</div>
<div id='parent-with-flex-direction-column'>
  <div class='child'>
  </div>
  <div class='child'>
  </div>
</div>