Lok*_*i00 5 javascript reactjs material-ui
我是 React 前端开发的新手。我正在尝试向我的 Material-UI 导航栏添加一个临时抽屉。我在代码中添加了一个抽屉:
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)
Run Code Online (Sandbox Code Playgroud)
但出现了这个错误:
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
Run Code Online (Sandbox Code Playgroud)
因此,我创建了一个构造函数来处理此问题(在渲染之前):
constructor(props) {
super(props);
this.state = {
open: false
};
}
Run Code Online (Sandbox Code Playgroud)
当我想改变状态时,我使用:
this.setState({ open: true })
Run Code Online (Sandbox Code Playgroud)
但是,当我触发抽屉(单击按钮)时,它没有打开。我能做些什么?
状态钩子 (useState) 可用于功能性 React 组件,但在您的情况下,您使用的是类组件。函数式 React 组件通常没有开箱即用的状态,但这useState是一个新功能,可以让您解决这个问题
您可以将其更改为功能组件,也可以将其保留为类组件并以不同的方式使用状态,例如:
!this.state.open而不是!open
和this.setState({open: false})代替setOpen(false)https://reactjs.org/docs/hooks-state.html
| 归档时间: |
|
| 查看次数: |
35522 次 |
| 最近记录: |