【发布时间】:2021-04-08 01:31:48
【问题描述】:
我正在尝试从打开模态的材料 UI 中组合一个反应组件。我有切换的状态,我在 chrome 的反应开发者控制台中看到切换从 false 变为 true,但是当我单击按钮时模式没有打开(按钮仅更改反应控制台验证的状态)。
import react from 'react'
import Modal from '@material-ui/core/Modal';
import Button from '@material-ui/core/Button';
import { withStyles } from "@material-ui/core/styles";
function rand() {
return Math.round(Math.random() * 20) - 10;
}
function getModalStyle() {
const top = 50 + rand();
const left = 50 + rand();
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`,
};
}
const styles = ((theme) => ({
paper: {
position: 'absolute',
width: 400,
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
class ModalTest extends react.Component {
state = {
modalToggle: false
}
componentDidMount(){
}
handleOpen = () => this.setState({modalToggle: true})
handleClose = () => this.setState({modalToggle: false})
renderModalBody(){
return (
<div style={getModalStyle()} className={styles.paper}>
<h2 id="simple-modal-title">Text in a modal</h2>
<p id="simple-modal-description">
This is a test of modal.
</p>
</div>
);
}
renderActionButtons(){
return <Button onClick={this.handleOpen} style={{margin: 0, position: 'absolute',
top: '50%', left: '50%' }} variant="contained" color="primary">Open Modal</Button>
}
renderModal(){
<Modal open={this.state.modalToggle} onClose={this.handleClose}>{this.renderModalBody()}</Modal>
}
render(){
return this.renderActionButtons()
}
}
export default withStyles(styles, { withTheme: true })(ModalTest)
【问题讨论】:
-
关于显而易见的危险:您没有在渲染函数中调用 renderModal。所以模态只是不存在。
标签: javascript reactjs material-ui react-material