【发布时间】:2020-02-10 06:01:17
【问题描述】:
我正在尝试将材料 ui 组件用于基于反应类的组件材料 ui 组件演示一切基于函数,但我们编写的所有项目页面都是基于类的,很难集成材料 UI 组件
【问题讨论】:
-
为什么要使用类组件?我认为功能组件的执行速度太快了。@user2829028
标签: material-ui
我正在尝试将材料 ui 组件用于基于反应类的组件材料 ui 组件演示一切基于函数,但我们编写的所有项目页面都是基于类的,很难集成材料 UI 组件
【问题讨论】:
标签: material-ui
在基于类的组件上集成并不难。是的,在 Material UI 文档中,所有东西都使用 Hooks 集成在基于功能的组件上。但是你应该有一些关于钩子和状态概念的知识,然后你就可以很容易地集成它们。 例如:
export default function AlertDialog() {
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div>
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
Open alert dialog
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Use Google's location service?"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Let Google help apps determine location. This means sending anonymous location
data to
Google, even when no apps are running.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Disagree
</Button>
<Button onClick={handleClose} color="primary" autoFocus>
Agree
</Button>
</DialogActions>
</Dialog>
</div>
);
}
所以,这个对话框代码是用基于函数的组件编写的,但是我们可以很容易地集成在基于类的组件上,比如:
export default class AlertDialog extends React.Components{
constructor(){
super(props)
this.state={
open:false
}
}
handleClickOpen = () => {
this.setState({open:true})
};
handleClose = () => {
this.setState({open:false})
};
render(){
return (
<div>
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
Open alert dialog
</Button>
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Use Google's location service?"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Let Google help apps determine location. This means sending anonymous location
data to
Google, even when no apps are running.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Disagree
</Button>
<Button onClick={this.handleClose} color="primary" autoFocus>
Agree
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
所以,只要我们了解基本的 React 概念,你就可以做到这一点。
【讨论】: