我是 React Frontend 开发的新手。我正在尝试向我的 Material-UI NavBar 添加一个临时抽屉。我在我的代码中添加了一个抽屉:
class Navbar extends Component {
render() {
const { authenticated } = this.props;
const [open, setOpen] = useState(false);
const handleDrawer = () =>{
setOpen(true)
}
return (
<AppBar position="fixed">
<Toolbar className="nav-container">
{authenticated ? (
<Fragment>
<IconButton edge="start" onClick={handleDrawer} >
<Menu/>
</IconButton>
<Drawer
anchor='left'
open={open}
onClose={()=> setOpen(false)}
>
<h3> Drawer</h3>
</Drawer>
<NewPost/>
<Link to="/">
<MyButton tip="Home">
<HomeIcon color = "disabled"/>
</MyButton>
</Link>
<Link to="/chats">
<MyButton tip="Chats">
<ChatIcon color = "disabled"/>
</MyButton>
</Link>
<Notifications />
</Fragment>
):(
<Fragment>
<Button color="inherit" component={Link} to="/login">Login</Button>
<Button color="inherit" component={Link} to="/signup">Singup</Button>
<Button color="inherit" component={Link} to="/">Home</Button>
{/* <Button color="inherit" component={Link} to="/user">Profile</Button>*/}
</Fragment>
)}
</Toolbar>
</AppBar>
)
}
}
Navbar.propTypes = {
authenticated: PropTypes.bool.isRequired
}
const mapStateToProps = state =>({
authenticated: state.user.authenticated
})
export default connect(mapStateToProps)(Navbar)
但是出现了这个错误:
React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function
所以,我创建了一个构造函数来处理这个(渲染之前):
constructor(props) {
super(props);
this.state = {
open: false
};
}
当我想改变状态时,我使用了:
this.setState({ open: true })
但是,当我触发抽屉(单击按钮)时,它没有打开。我能做什么?
状态钩子 (useState) 可用于功能性 React 组件,但在您的情况下,您使用的是 Class 组件。函数式 React 组件通常没有开箱即用的状态,但它useState
是一项新功能,可以让您解决这个问题
您可以将其更改为功能组件,也可以将其保留为类组件并以不同的方式使用状态,例如:
!this.state.open
而不是!open
和this.setState({open: false})
代替 setOpen(false)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句