使用按钮 React 创建模式,Material UI

creating a modal with a button, React, Material UI

这是我在这里的第一个问题 :) 我是 React 的新手,有一个简单的问题。我只是想添加一个创建模态框的新函数,然后在您按下添加图标时调用它 onClick(第 43 行)。谢谢! P.S。我已经尝试了几种不同的方法,但总是出现白屏 :P

export default class Dayview extends Component {
    constructor() {
      super();
  
      this.employees = ['Qwynn'];
      this.hourparams = [9,19];
      this.weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
      this.months = ['January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'];
  
      this.state = {
        currentDay: new Date()
      }
    }
  
    changeCurrentDay = (day) => {
      this.setState({ currentDay: new Date(day.year, day.month, day.number) });
    }
  
    nextMonth = () => {
      this.setState({ currentDay: new Date(this.state.currentDay.setDate(this.state.currentDay.getDate() + 28)) });
    }
  
    previousMonth = () => {
      this.setState({ currentDay: new Date(this.state.currentDay.setDate(this.state.currentDay.getDate() - 28)) });
    }

    addAppt = () => {
      
    }
  
    render() {
      return (
        <div>
            <div className="dayview-header">
            <div className="title">
            <h2>{this.months[this.state.currentDay.getMonth()]} {this.state.currentDay.getFullYear()}</h2>
          </div>
          <div className="tools">
          <button onClick={this.previousMonth}>
              <AddBoxIcon className="material-icons"/>
            </button>
            <button onClick={this.previousMonth}>
              <ArrowBackIcon className="material-icons"/>
            </button>
            <p>{this.months[this.state.currentDay.getMonth()].substring(0, 3)} {this.state.currentDay.getDate()}</p>
            <button onClick={this.nextMonth}>
              <ArrowForwardIcon className="material-icons"/>
            </button>
          </div>
            </div>
            <DayviewHours />
        </div>
        
      )
    }
  }

因为你正在使用 class 组件,首先你需要 declare/initialize 在你的 this.state 构造函数中创建一个 open 对象来控制 modal 是否是打开或关闭。它的默认值应该是 false,

this.state = {
  currentDay: new Date(),
  open: false
};

在Modal组件中,可以传入open状态作为prop来控制模态,

<Modal
    open={this.state.open}
    onClose={this.handleClose}
>

这是你的按钮,

<button onClick={this.handleOpen}>
     <AddBoxIcon className="material-icons" />
</button>

要打开模式,

handleOpen = () => {
    this.setState({ open: true });
};

要关闭模式,您可以使用 MUI 文档提供的 onClose 道具,

Callback fired when the component requests to be closed. The reason parameter can optionally be used to control the response to onClose

  handleClose = () => {
    this.setState({ open: false });
  };

codesandbox 中的完整代码:Demo