5 回答

TA貢獻1829條經驗 獲得超7個贊
狀態鉤子 (useState) 可用于功能性 React 組件,但在您的情況下,您使用的是類組件。函數式 React 組件通常沒有開箱即用的狀態,但這useState
是一個新功能,可以讓您解決這個問題
您可以將其更改為功能組件,也可以將其保留為類組件并以不同的方式使用狀態,例如:
!this.state.open
而不是!open
和this.setState({open: false})
代替setOpen(false)
https://reactjs.org/docs/hooks-state.html

TA貢獻1846條經驗 獲得超7個贊
將此行更改const [open, setOpen] = useState(false);
為this.state = { open: false };
當設置為 true 時,只需調用 this.setState({ open: this.state.open: true })

TA貢獻1815條經驗 獲得超6個贊
您必須使用功能組件。目前你的組件是一個類組件,所以你應該有類似的東西:
const Navbar = (props) => {
const { authenticated } = props;
const [open, setOpen] = useState(false);
const handleDrawer = () =>{
setOpen(true)
}
return (
<AppBar position="fixed">...</AppBar>
);
};
我還注意到您的類組件具有在渲染方法中定義的狀態部分。使用類組件時,應該在constructor中定義狀態,否則每次渲染時您的狀態都會被覆蓋。

TA貢獻1794條經驗 獲得超8個贊
使用function Navbar(props)
代替class Navbar extends Component
這是因為,有一個規則:React Hook“useState”不能在class component
eg中調用class Navbar extends Component
。React function component
React Hooks 必須在例如function Navbar(props)
或自定義 React Hook 函數中調用

TA貢獻1790條經驗 獲得超9個贊
函數組件而不是類組件怎么樣?如您所知,推薦使用功能組件。我認為它很容易編碼并且可以提高性能。
const Navbar = () => {
//useState, define functions here
return (//the same as render method of your class component)
}
添加回答
舉報