首页 > 解决方案 > 如何在反应js中使用flex在每个角落排列两个按钮

问题描述

我是 React js 的新手。刚开始构建一个简单的 react 应用程序。我在每一侧都有两个按钮,我试图用 CSS-flex 做,但无法实现。任何人都可以建议我哪里出错了吗?

      import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";



const styles = {
  root: {
    display:'flex',
    justifyContent: 'space-between',
    width:'100%'
  },

};

class Header extends Component {
  render() {
    return (
    <div className={styles.root}>
   <button>news</button>
   <button >login</button>
</div>
    );
  }
}

export default Header;

两个图标,即新闻和登录应该在 AppBar 的两个角落。

下面是我现在得到的视图

标签: cssreactjs

解决方案


更新

您在className应该使用该style属性时使用。您正在设置样式,而不是课程。

React 代码看起来像这样:

class Header extends React.Component {

  render() {
    const styles = {
      root: {
        display:'flex',
        justifyContent: 'space-between',
        width:'100%'
      }    
    }

    return (
      <div style={styles.root}>
        <button>news</button>
        <button >login</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.querySelector("#app"))

工作的小提琴就在这里


您的 flex 容器在 DOM 中的位置太高了。由于 flex 子项必须是 flex 父项的直接后代,因此您所拥有的将不起作用。您需要将display: flex分配向下移动到<Toolbar>,因为它是and的直接父级。要使用 flex 对齐对角的两个按钮,可以使用.<Button><Typography>justify-content: space-between

.container {
  display: flex;
  justify-content: space-between;
}
<div class="container">
   <button>a button</button>
   <button>a button</button>
</div>

jsFiddle


推荐阅读