css - 如何在反应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 的两个角落。
解决方案
更新
您在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>
推荐阅读
- javascript - Google AdSense 审核不断返回,但没有内容错误(JavaScript 客户端呈现)
- javascript - 将多个json对象转换为对象数组
- html - 使用 HTML5 模式进行验证
- reactjs - react js创建本地数据库的方法
- mysql - MySQL 5.7.25 [innoDB],索引基数突然重置/变回 1
- c# - C# 字符串和数字正则表达式
- angular - Angular 9 与 ui 路由器混合导致尝试在设置 AngularJS 注入器之前获取它。如何调试/修复?
- python - 如何加速 Pandas 循环
- java - 如何使用while循环打印“*”n次?
- machine-learning - 使用 LinearRegression 进行预测时出现 ValueError