React Hooks-汉堡菜单



我试图使用React Hooks在我的项目网站上实现汉堡菜单,但在控制台中遇到了一些不同的错误。菜单只在启动时可见,按钮没有任何效果。

警告:失败的道具类型:提供给Burger的类型为object的道具open无效,应为boolean

警告:失败的道具类型:提供给Burger的类型为object的道具setOpen无效,应为function

未捕获类型错误:setOpen不是函数

请参阅下面的代码:

Burger.js

import React from 'react';
import { bool, func } from 'prop-types';
import { StyledBurger } from './BurgerStyles';
const Burger = ({ open, setOpen }) => {
return (
<StyledBurger open={open} onClick={() => setOpen(!open)}>
<div />
<div />
<div />
</StyledBurger>
)
}
Burger.propTypes = {
open: bool.isRequired,
setOpen: func.isRequired,
};
export default Burger;

菜单.js

import React from "react";
import { bool } from 'prop-types';
import { StyledMenu } from "./MenuStyles";
const Menu = ({ open }) => {
return (
<StyledMenu open={open}>
CONTENT
</StyledMenu>
)
}
Menu.propTypes = {
open: bool.isRequired,
}
export default Menu;

menu.js的移动在样式组件中使用处理

transform: ${({ open }) => open ? 'translateX(0)' : 'translateX(100%)'};

App.js

import React, { useState } from 'react';
import Header from "./components/Header/Header";
import Menu from "./components/Menu/Menu";
const App = () => {
const [open, setOpen] = useState(false);
return (
<>
<Menu open={open} setOpen={setOpen} />
<Header open={open} setOpen={setOpen} />
</>
)
}
export default App;

Header.js

import React, {useState} from 'react';
import Burger from '../Burger/Burger';

const Header = (open, setOpen) => (
<div>
<Burger open={open} setOpen={setOpen} />
</div>
)

感谢任何帮助,谢谢!!

Header.js中,道具没有被销毁,所以open实际上是props对象。

// It should be this
const Header = ({ open, setOpen }) => (
// Not this
const Header = (open, setOpen) => (

相关内容

  • 没有找到相关文章

最新更新