我正在通过阅读React wiki和遵循freeCodeCamp的例子来学习React,但是我偶然发现了这个问题,我似乎不能理解我可能错过了什么。
我的意图是有一个面板的按钮,当你点击其中一个组件显示或隐藏。
import React, { Component, useState } from "react";
import { Box, Typography, Stack, Button, Divider } from '@mui/material';
import ListUsers from '../components/ListUsers'
import ListTasks from "../components/ListTasks";
class Admin extends Component {
constructor() {
super();
this.state = {
/*Start with all components hidden*/
toogleShowAllUsers: false,
toogleShowAllTasks: false
};
this.changeState = this.changeState.bind(this)
}
changeState(name) {
console.log(name)
switch(name) {
case 'toogleShowAllUsers':
this.state = ({ toogleShowAllUsers: !this.state.toogleShowAllUsers })
break;
case 'toogleShowAllTasks':
this.state = ({ toogleShowAllTasks: !this.state.toogleShowAllTasks })
break;
default:
}
}
render() {
const { toogleShowAllUsers, toogleShowAllTasks } = this.state
return (
/*Options menu*/
<Box>
<Typography
variant="h4"
fontWeight="bold"
sx={{ fontSize: { lg: '44px', xs: '30px' } }}
mb="46px">Admin Panel
</Typography>
<Stack
direction="row"
divider={<Divider
orientation="vertical"
flexItem
sx={{bgcolor: "secondary.light"}}/>}
spacing={2}>
<Button>Crear usuario</Button>
<Button>Eliminar usuario</Button>
<Button onClick={() => this.changeState('toogleShowAllUsers')}>Listar Usuarios</Button>
</Stack>
<Stack
direction="row"
divider={<Divider
orientation="vertical"
flexItem
sx={{bgcolor: "secondary.light"}}/>}
spacing={2}>
<Button>Crear tarea</Button>
<Button>Eliminar tarea</Button>
<Button>Asignar tarea</Button>
<Button onClick={() => this.changeState('toogleShowAllTasks')}>Listar Tareas</Button>
</Stack>
{/*Render options here*/}
{toogleShowAllUsers ? <ListUsers /> : null}
{toogleShowAllTasks ? <ListTasks /> : null}
</Box>
)
}
}
export default Admin;
我已经检查了SO here和here上的类似问题,但没有结果。
我会很感激,如果你能帮助/指导我了解我可能错过了什么或我什么时候做错了,以学习这个可怕的工具。
1条答案
按热度按时间ohfgkhjo1#
快速修复,应为.setState({ })
有关在类组件中使用状态的详细信息
React测试版文档是functional components和managing state in function components的良好起点
希望能有所帮助,