You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否不使用JSX语法,仅用JavaScript、MUI Dialog等技术创建弹窗?

不使用JSX创建MUI弹窗的实现方法

当然可以。React本身支持通过React.createElement()方法替代JSX语法创建组件,MUI的所有组件(包括Dialog)都能通过这种方式直接调用,无需依赖JSX编译。

以下是完整的实现示例:

// 导入所需依赖
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material';

// 创建无JSX的弹窗组件
const MuiDialogWithoutJSX = () => {
  const [open, setOpen] = React.useState(false);

  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  return React.createElement(Dialog, {
    open: open,
    onClose: handleClose,
    aria-labelledby: "dialog-title"
  }, [
    React.createElement(DialogTitle, { id: "dialog-title" }, "MUI弹窗(无JSX)"),
    React.createElement(DialogContent, null, "这是完全用JavaScript创建的MUI弹窗,未使用JSX语法。"),
    React.createElement(DialogActions, null, [
      React.createElement(Button, { onClick: handleClose, color: "primary" }, "取消"),
      React.createElement(Button, { onClick: handleClose, color: "primary", autoFocus: true }, "确认")
    ])
  ]);
};

// 将弹窗渲染到DOM节点
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(MuiDialogWithoutJSX));

关键说明:

  • React.createElement(type, props, children)是JSX的底层实现:第一个参数为组件类型(如MUI的Dialog),第二个为组件props,第三个及后续参数(或数组)为子元素。
  • 当存在多个子元素时,需将其放入数组中传递。
  • MUI组件的props规则与使用JSX时完全一致,open、onClick等属性可直接传递。

内容的提问来源于stack exchange,提问作者kum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:02:20