我想把这个类转换成一个函数,但是它失败了:
class MyClass extends Component {
state = { settings: [{ id: "1", open: false }, { id: "2", open: false }] };
handleClick = id => {
this.setState(state => ({
...state,
settings: state.settings.map(item => item.id === id ? { ...item, open: !item.open } : item
)
}));
};
render() {
const { settings } = this.state;
return (
<div style={{ marginRight: "15px" }}>
<core.List component="nav">
{myData.map(each => (
<React.Fragment key={each.id}>
<core.ListItem button onClick={() => this.handleClick(each.id)}>
<core.ListItemText inset primary={each.nameHeader} />
{settings.find(item => item.id === each.id).open
? "expanded"
: "collapsed"}
</core.ListItem>
<core.Divider />
<core.Collapse
in={settings.find(item => item.id === each.id).open}
timeout="auto"
unmountOnExit
>
<core.List component="div" disablePadding>
{each.subMenu.map(subData => (
<core.ListItem key={subData.id} button>
<core.ListItemText inset primary={subData.name} />
</core.ListItem>
))}
</core.List>
</core.Collapse>
</React.Fragment>
))}
</core.List>
</div>
);
}
}
export default MyClass;
以前使用mui(旧版本):
import React, { Component } from "react";
import * as core from "@material-ui/core";
import { myData } from "./myData";
我想在映射时分别打开和关闭每个项目。
当它变成一个函数时没有执行,或者我没有正确转换它!
谢谢你的帮助。
基本上,您希望将componentDidUpdate
和componentDidMount
转换为useEffect
,并将所有状态变量转换为useState
。此外,您不需要this.
。
在你的例子中:
import {useState} from 'react'
const MyClass = props => {
const [settings, setSettings] = useState([{ id: "1", open: false }, { id: "2", open: false }])
handleClick = id => {
setSettings(oldSettings => (
oldSettings.map(item => item.id === id ? { ...item, open: !item.open } : item)
);
};
return (
<div style={{ marginRight: "15px" }}>
<core.List component="nav">
{myData.map(each => (
<React.Fragment key={each.id}>
<core.ListItem button onClick={() => handleClick(each.id)}>
<core.ListItemText inset primary={each.nameHeader} />
{settings.find(item => item.id === each.id).open
? "expanded"
: "collapsed"}
</core.ListItem>
<core.Divider />
<core.Collapse
in={settings.find(item => item.id === each.id).open}
timeout="auto"
unmountOnExit
>
<core.List component="div" disablePadding>
{each.subMenu.map(subData => (
<core.ListItem key={subData.id} button>
<core.ListItemText inset primary={subData.name} />
</core.ListItem>
))}
</core.List>
</core.Collapse>
</React.Fragment>
))}
</core.List>
</div>
);
}
export default MyClass;