我是 React 的新手,在网站上。我有一个我不明白的问题。 我想拆卸我的道具,这样我会更舒服地使用它,这是我第一次为功能组件这样做。我总是使用类组件。
这是我写下的代码,我得到了道具,我打印了它并且它存在。我想解压props,不是每次都列出props.classes.root,我只想列出classes.root。
这就是我所做的,但它对我不起作用,我正在尝试注册 classes.root - 我收到一个错误,它没有设置,但 props.classes.root 工作正常。我不明白为什么
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Checkbox from '@material-ui/core/Checkbox';
import Avatar from '@material-ui/core/Avatar';
import withStyles from '@material-ui/core/styles/withStyles';
//Redux
import { connect } from 'react-redux';
const styles = (theme) => ({
...theme.spreadThis
});
function PreferenceList(props) {
const {
user: {
classes
}
} = props;
console.log(props.classes);
const [checked, setChecked] = React.useState([1]);
const handleToggle = (value) => () => {
const currentIndex = checked.indexOf(value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(value);
} else {
newChecked.splice(currentIndex, 1);
}
setChecked(newChecked);
};
return (
<List dense className={classes.root}>
{[0, 1, 2, 3].map((value) => {
const labelId = `checkbox-list-secondary-label-${value}`;
return (
<ListItem key={value} button>
<ListItemAvatar>
<Avatar
alt={`Avatar n°${value + 1}`}
src={`/static/images/avatar/${value + 1}.jpg`}
/>
</ListItemAvatar>
<ListItemText id={labelId} primary={`Line item ${value + 1}`} />
<ListItemSecondaryAction>
<Checkbox
edge="end"
onChange={handleToggle(value)}
checked={checked.indexOf(value) !== -1}
inputProps={{ 'aria-labelledby': labelId }}
/>
</ListItemSecondaryAction>
</ListItem>
);
})}
</List>
);
}
const mapStateToProps = (state) => ({
user: state.user
});
export default connect(
mapStateToProps
)(withStyles(styles)(PreferenceList));
答案 0 :(得分:1)
试试,
//Object destructuring
const { classes } = props;
然后你可以做,classes.root
,鉴于你提到的,props.classes.root
有效。
答案 1 :(得分:1)
根据你所说,这是错误的行
const {
user: {
classes
}
} = props;
应该是
const {
classes
} = props;
不确定您从哪里获得该用户部分?
顺便说一句,这个方法叫做解构。