gpt4 book ai didi

reactjs - 将扩展面板功能组件转换为类组件

转载 作者:行者123 更新时间:2023-12-03 14:30:37 26 4
gpt4 key购买 nike

我的 react 相对较新。我一直在尝试为下面的 Accordion 扩展面板创建一个功能格式的类组件。我无法根据类组件更改handleChange 事件。我已经尝试了所有可能的方法,但我失败了。

 import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

const useStyles = makeStyles(theme => ({

}));

export default function ControlledExpansionPanels() {


const classes = useStyles();

const [expanded, setExpanded] = React.useState(false);


const handleChange = panel => (event, isExpanded) => {
setExpanded(isExpanded ? panel : false);
};


return (

<div className={classes.root}>

<ExpansionPanel expanded={expanded === 'panel1'} onChange={handleChange('panel1')}>

<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1bh-content"
id="panel1bh-header"
>


</ExpansionPanelSummary>
<ExpansionPanelDetails>

</ExpansionPanelDetails>
</ExpansionPanel>
<ExpansionPanel expanded={expanded === 'panel2'} onChange={handleChange('panel2')}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel2bh-content"
id="panel2bh-header"
>

</ExpansionPanelSummary>
<ExpansionPanelDetails>

</ExpansionPanelDetails>
</ExpansionPanel>


</div>

);

}

请帮忙!

最佳答案

会是这样的

 export default class ControlledExpansionPanels extends React.Component {


// const classes = useStyles();// // you can't use custom hook in class Component //

const [expanded, setExpanded] = React.useState(false); // previous hook now not needed //

state = { expanded: false }




handleChange = panel => (event, isExpanded) => {
// setExpanded(isExpanded ? panel : false); // //previous state manager , now not needed //
isExpanded ? this.setState({ expanded: panel}) : this.setState({ expanded: false }) //new state manager//
};

render() {
return (

<div className={classes.root}>

<ExpansionPanel expanded={this.state.expanded === 'panel1'} onChange={this.handleChange('panel1')}>

<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1bh-content"
id="panel1bh-header"
>


</ExpansionPanelSummary>
<ExpansionPanelDetails>

</ExpansionPanelDetails>
</ExpansionPanel>
<ExpansionPanel expanded={this.state.expanded === 'panel2'} onChange={this.handleChange('panel2')}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel2bh-content"
id="panel2bh-header"
>

</ExpansionPanelSummary>
<ExpansionPanelDetails>

</ExpansionPanelDetails>
</ExpansionPanel>


</div>
)}

我认为这应该可行..除了你自己的钩子(Hook)之外一切都很好。

关于reactjs - 将扩展面板功能组件转换为类组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57669590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com