大家好,我是前端开发的初学者,我需要做出响应式导航栏。我发现一些在 html 中有效但在 react 中无效。我不知道我能不能走这条路。我认为问题出在 getElementById 上,因为 react 不支持它们。
import React from "react";
import { Link } from "react-router-dom";
import "./index.css";
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
function Header() {
return (
<nav>
<div className="topnav" id="myTopnav">
<a href="#home" className="active">
Home
</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" className="icon" onclick={myFunction}>
<i className="fa fa-bars"></i>
</a>
</div>
</nav>
);
}
export default Header;
答案 0 :(得分:1)
更新
将 myFunction()
放在 Header()
中,因为这是一个基于函数的组件。
这里是 Header
组件更改后的样子:
import React from "react";
import { Link } from "react-router-dom";
import "./index.css";
function Header() {
const myFunction = () => {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
return (
<nav>
<div className="topnav" id="myTopnav">
<a href="#home" className="active">
Home
</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" className="icon" onClick={myFunction}>
<i className="fa fa-bars"></i>
</a>
</div>
</nav>
);
}
export default Header;
请访问此链接查看:Code Sandbox Live Demo
答案 1 :(得分:0)
这是css
.topnav {
overflow: hidden;
background-color: black;
}
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav .icon {
display: none;
}
@media screen and (max-width: 600px) {
.topnav a {
display: none;
}
.topnav a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 600px) {
.topnav.responsive {
position: relative;
}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}