如何在 ReactJS 中使用多个对话框和渲染模式 [英] How to use multiple dialog boxes and render modals in ReactJS

查看:22
本文介绍了如何在 ReactJS 中使用多个对话框和渲染模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何使用 Material UI 的对话框来呈现模态框,在单击按钮时关闭它们,以及如何让点击不同的东西会显示不同的模态框.

这是我从 Material UI 中获取的对话框组件

import React from 'react';从'@material-ui/core/Button'导入按钮;从'@material-ui/core/Dialog'导入对话框;从@material-ui/core/DialogActions"导入 DialogActions;从@material-ui/core/DialogContent"导入 DialogContent;从@material-ui/core/DialogContentText"导入 DialogContentText;从@material-ui/core/DialogTitle"导入 DialogTitle;类对话框扩展 React.Component {使成为() {返回 (<对话打开={this.props.open}onClose={this.props.handleClose}aria-labelledby="alert-dialog-title"aria- describeby =警报对话框描述"><DialogTitle id="alert-dialog-title">{"使用 Google 的定位服务?"}</DialogTitle><对话内容><DialogContentText id="alert-dialog-description">让 Google 帮助应用确定位置.这意味着将匿名位置数据发送到谷歌,即使没有应用程序正在运行.</对话内容文本></对话内容><对话动作><按钮 onClick={this.props.handleClose} color="primary">好的</按钮></DialogActions></对话>);}}导出默认对话框;

这是我在其中渲染对话框的页面,我在这里称之为 Modal.如何制作它以便在对话框打开时关闭它,并且我可以点击不同的图片并让它打开一个带有不同文本的对话框?

import React,{Component} from "react";从./home.png"导入主页;从./car.png"导入汽车;从./bed.png"导入床;从./pet.png"导入宠物;从./Modal.js"导入对话框;类场景扩展组件{构造函数(){极好的();this.state = { open: false };}openModal = () =>{this.setState({ open: true });}句柄关闭 = () =>{this.setState({ open: false });};使成为() {返回 (<section className="应用场景"><h2>快速提示 </h2><p>了解地震期间不同情景下的应对措施</p><div className="场景组"><div className="scenario" onClick={this.openModal}><img src={汽车}/></div><div className="scenario" onClick={this.openModal}><img src={home}/><对话框打开={this.state.open} onClose={this.handleClose} title="Home" description="text"/></div><div className="场景" ><img src={床}/></div><div className="场景"><img src={宠物}/></div></div></部分>);}};导出默认场景;

解决方案

你有一个很好的开始,但是你缺少一些东西.您只需要使您的组件更加灵活和可重用(请参阅下面的评论).

一些注意事项:下面的示例使用

<小时>

组件/模态

从react"导入反应;从prop-types"导入 PropTypes;进口 {按钮,对话,对话动作,对话内容,对话框内容文本,对话标题} 来自@material-ui/core";//"模态是一个纯函数,需要4个参数才能显示//"<模态/>"零件.此功能与传统功能相同:////function Modal({ 解构参数 }) {//    返回 (//<对话框>//...//</对话框>//)//}const Modal = ({ description, onCloseModal, openModal, title }) =>(<对话打开={openModal}onClose={onCloseModal}aria-labelledby="alert-dialog-title"aria- describeby =警报对话框描述"><DialogTitle id="alert-dialog-title">{title}</DialogTitle><对话内容><DialogContentText id="alert-dialog-description">{描述}</对话内容文本></对话内容><对话动作><按钮 onClick={onCloseModal} color="primary">好的</按钮></DialogActions></对话>);//如果 4 个必需参数中的任何一个是,PropTypes 将引发警告//失踪!此外,它确保道具名称一致//以及从父组件到子组件的声明.Modal.propTypes = {描述:PropTypes.string.isRequired,onCloseModal: PropTypes.func.isRequired,openModal: PropTypes.bool.isRequired,标题:PropTypes.string.isRequired};导出默认模态;

组件/场景

import React, { PureComponent } from "react";从prop-types"导入 PropTypes;//场景将是一个 PureComponent(无状态,但仍然是一个类组件)//这将使用提供的描述"打开 Modal 组件,并且//通过名为handleOpenModal"的父回调函数标题"类场景扩展 PureComponent {openModal = () =>{常量 { 描述,handleOpenModal,标题 } = this.props;handleOpenModal({ 描述, 标题 });};渲染 = () =>(<div className="scenario" onClick={this.openModal}><h1>{this.props.imgSrc}</h1></div>);}Scenario.propTypes = {描述:PropTypes.string.isRequired,handleOpenModal: PropTypes.func.isRequired,imgSrc: PropTypes.string.isRequired,标题:PropTypes.string.isRequired};导出默认场景;

组件/场景

import React, { Component } from "react";从../Modal"导入模态;从../Scenario/"导入场景;//一个对象数组的场景变量——使得我们不必这样做//重复 <Scenario title=".." description="..."imgSrc={...} handleOpenModal={..}/>//一遍又一遍,我们将这些对象映射为道具"并展开//它们在场景"中像这样:<Scenario {...props}/>,其中//将与以下内容相同://<场景标题={title} description={description} imgSrc={imgSrc}/>常量场景 = [{标题:汽车",description: "这是对汽车的描述.",imgSrc:汽车.png"},{标题:家",description: "这是对房屋的描述.",imgSrc:home.png"},{标题:床",description: "这是一张床的描述.",imgSrc:床.png"},{标题:宠物",description: "这是对宠物的描述.",imgSrc:宠物.png"}];//场景是一个有状态的类组件,它将作为父组件//为其场景"子级.孩子将通过以下方式更新父母//this.handleOpenModal".同时,Modal"将位于父级内部//等待父状态更新以影响其渲染方式.这//模态将通过父级的this.handleCloseModal"关闭自己//单击确定"按钮时的类方法.类场景扩展组件{state = { description: "", openModal: false, title: "" };handleOpenModal = ({ 描述, 标题 }) =>{this.setState({ description, openModal: true, title });};handleCloseModal = () =>{this.setState({ openModal: false });};渲染 = () =>(<section className="应用场景"><h2>快速提示 </h2><p>了解地震期间不同情景下的应对措施</p><div className="场景组">{scenarios.map(props => (<情景{...道具}key={props.title}//React 需要知道map"函数返回的每个场景"都是唯一的,并且必须作为单独的组件处理(否则 React 会抱怨并抛出警告)handleOpenModal={this.handleOpenModal}/>))}</div><模态 {...this.state} onCloseModal={this.handleCloseModal}/></部分>);}导出默认场景;

I'm having trouble figuring out how to use Material UI's dialog box to render modals, close them upon button clicking and also make it so that clicking on different things brings up different modals.

This is the dialog component that I took from Material UI

import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';


class DialogBox extends React.Component {

  render() {
    return (
      <Dialog
      open={this.props.open}
      onClose={this.props.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.props.handleClose} color="primary">
          Okay
        </Button>
      </DialogActions>
    </Dialog>
    );
  }
}


export default DialogBox;

This is the page that I am rendering the Dialog Box in, I called it Modal in here. How do I make it so that I can close it when the dialog is open and also so I can click on a different picture and have it open up a dialog with different text?

import React,{Component} from "react";
import home from "./home.png";
import car from "./car.png";
import bed from "./bed.png";
import pet from "./pet.png";
import Dialog from "./Modal.js";

class Scenarios extends Component {
  constructor(){
    super();
    this.state = { open: false };
  }

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

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

  render() {
    return (
       <section className="App-scenarios">
        <h2> Quick Tips </h2>
        <p>Know What to Do in Different Scenarios during an Earthquake</p>
        <div className="scenario-group">

          <div className="scenario" onClick={this.openModal}>
            <img src={car}/>
          </div> 

          <div className="scenario" onClick={this.openModal}>
          <img src={home}/>
            <Dialog open={this.state.open} onClose={this.handleClose} title="Home" description="text" />
          </div>
          <div className="scenario" >
          <img src={bed}/>
          </div>
          

          <div className="scenario">
          <img src={pet}/>
          </div>
        </div>
      </section>
    );
    }
};

export default Scenarios;

解决方案

You have a great start, but you're missing a few items. You just need to make your components more flexible and reusable (see below for comments).

Some notes: The example below uses ES6 destructuring, ES6 Fat Arrow Functions, the map function, the spread operator, and callback functions. In addition, you can't wrap a clickable element (Modal) inside of another clickable element (div). The outer most element (div) will only be handled by the onClick event handler.

Working example (for simplicity, I'm not using images, instead I'm using placeholder example.png titles that are clickable):


components/Modal

import React from "react";
import PropTypes from "prop-types";
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle
} from "@material-ui/core";


// "Modal is a pure function that requires 4 parameters in order to display 
// the "<Modal />" component. This function would be the same as a traditional function:
// 
//   function Modal({ deconstructed parameters }) { 
//     return (
//       <Dialog>
//        ...
//      </Dialog>
//     )
//   }

const Modal = ({ description, onCloseModal, openModal, title }) => ( 
  <Dialog
    open={openModal}
    onClose={onCloseModal}
    aria-labelledby="alert-dialog-title"
    aria-describedby="alert-dialog-description"
  >
    <DialogTitle id="alert-dialog-title">{title}</DialogTitle>
    <DialogContent>
      <DialogContentText id="alert-dialog-description">
        {description}
      </DialogContentText>
    </DialogContent>
    <DialogActions>
      <Button onClick={onCloseModal} color="primary">
        Okay
      </Button>
    </DialogActions>
  </Dialog>
);

// PropTypes throws a warning if any of the 4 required params are
// missing! In addition, it ensures that props are consistent in name
// and declaration from parent component to child component.

Modal.propTypes = {
  description: PropTypes.string.isRequired,
  onCloseModal: PropTypes.func.isRequired,
  openModal: PropTypes.bool.isRequired,
  title: PropTypes.string.isRequired
};

export default Modal;

components/Scenario

import React, { PureComponent } from "react";
import PropTypes from "prop-types";


// Scenario will be a PureComponent (stateless, but still a class component) 
// that will open the Modal component with a supplied "description" and 
// "title" via a parent callback function named "handleOpenModal"

class Scenario extends PureComponent {
  openModal = () => {
    const { description, handleOpenModal, title } = this.props;
    handleOpenModal({ description, title });
  };

  render = () => (
    <div className="scenario" onClick={this.openModal}>
      <h1>{this.props.imgSrc}</h1>
    </div>
  );
}

Scenario.propTypes = {
  description: PropTypes.string.isRequired,
  handleOpenModal: PropTypes.func.isRequired,
  imgSrc: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired
};

export default Scenario;

components/Scenarios

import React, { Component } from "react";
import Modal from "../Modal";
import Scenario from "../Scenario/";

// A scenarios variable of an array of objects -- makes it so we don't have to 
// repeat <Scenario title=".." description="..."imgSrc={...} handleOpenModal={..} /> 
// over and over, instead we map over these objects as "props" and spread
// them out inside of "Scenario" like so: <Scenario {...props} />, which 
// would be the same as:  
// <Scenario title={title} description={description} imgSrc={imgSrc} />

const scenarios = [
  {
    title: "Car",
    description: "This is a description for a car.",
    imgSrc: "car.png"
  },
  {
    title: "Home",
    description: "This is a description for a home.",
    imgSrc: "home.png"
  },
  {
    title: "Bed",
    description: "This is a description for a bed.",
    imgSrc: "bed.png"
  },
  {
    title: "Pet",
    description: "This is a description for a pet.",
    imgSrc: "pet.png"
  }
];

// Scenarios is a stateful class component that'll act as the parent 
// for its "Scenario" children. The children will update the parent via 
// "this.handleOpenModal". Meanwhile, "Modal" will sit inside the parent
// waiting for the parent state updates to affect how its rendered. The 
// Modal will close itself via the parent's "this.handleCloseModal"
// class method when the "Okay" button is clicked.

class Scenarios extends Component {
  state = { description: "", openModal: false, title: "" };

  handleOpenModal = ({ description, title }) => {
    this.setState({ description, openModal: true, title });
  };

  handleCloseModal = () => {
    this.setState({ openModal: false });
  };

  render = () => (
    <section className="App-scenarios">
      <h2> Quick Tips </h2>
      <p>Know What to Do in Different Scenarios during an Earthquake</p>
      <div className="scenario-group">
        {scenarios.map(props => (
          <Scenario
            {...props}
            key={props.title} // this is required for React to know that each "Scenario" that is returned by the "map" function is unique and must be handled as individual components (otherwise React will complain and throw a warning)
            handleOpenModal={this.handleOpenModal}
          />
        ))}
      </div>
      <Modal {...this.state} onCloseModal={this.handleCloseModal} />
    </section>
  );
}

export default Scenarios;

这篇关于如何在 ReactJS 中使用多个对话框和渲染模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆