获取类型错误: 无法设置未定义的属性'state'



我得到无法设置属性错误。如果我从 this.state 中删除它,它会给出错误,例如"状态"没有定义 no-undef。 解决这个问题。提前谢谢。导入语句在那里。 错误: 类型错误: 无法将属性"状态"设置为未定义。

this.state = {
anchorEl: null,
};
this.handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
this.handleClose = () => {
this.setState({ anchorEl: null });
};
function SimpleCard(props) {
const { classes } = props;
const { anchorEl } = this.state;
const open = Boolean(anchorEl);

return (
<Card className={classes.card}>
<CardHeader
action={
<IconButton aria-label="More"
aria-owns={open ? 'long-menu' : null}
aria-haspopup="true"
onClick={this.handleClick}>
<MoreVertIcon />
<Menu
id="long-menu"
anchorEl={anchorEl}
open={open}
onClose={this.handleClose}
PaperProps={{
style: {
maxHeight: ITEM_HEIGHT * 4.5,
width: 100,
},
}}
>
{options.map(option => (
<MenuItem key={option} selected={option === 'Pyxis'} onClick={this.handleClose}>
{option}
</MenuItem>
))}
</Menu>
</IconButton>
}
title={props.products.title}
/>
<CardContent>
<Typography component="p">
{props.products.id}
</Typography>
</CardContent>
</Card>
);
}
SimpleCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleCard);

handleClosehandleClick是函数,而不是对象的方法:在它们内部使用this没有开箱即用的真正意义,你没有使用功能组件的状态。

最简单的解决方法是切换到基于类的组件:

class SimpleCard extends React.PureComponent {
this.handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
}
handleClose = () => {
this.setState({ anchorEl: null });
}
render() {
// your current SimpleCard code here
}
}

最新更新