首页 > 解决方案 > 未能分解功能组件中的道具

问题描述

我是 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));


标签: javascriptreactjs

解决方案


尝试,

   //Object destructuring
   const { classes } = props;

然后你可以做 , classes.root,鉴于你提到的,props.classes.root作品。


推荐阅读