如何在React中通过innerHTML添加样式正常生效的Material-UI组件
问题根源
<Button>是Material UI封装的React组件,不是原生HTML标签,你通过innerHTML插入的只是纯文本字符串,浏览器不会走React的组件渲染逻辑,自然无法加载Material UI的样式,绑定的onClick事件也不会生效。- 手动操作DOM修改页面内容不符合React的声明式渲染规范,很容易导致视图和内部状态不同步,出现各种不可预期的问题。
修复方案
你只需要在接口请求成功后把用户数据存到state的users字段里,render的时候直接遍历users渲染表格行即可,完全不需要手动操作DOM:
import React, { Component } from 'react'; import axios from 'axios'; import Button from '@mui/material/Button'; // 确保已正确引入Button组件 class CRUD extends Component { state = { switchStatus: false, users: [], findOneTime: false, } switch = () => { this.setState({ switchStatus: !this.state.switchStatus, }) } allUser = () => { if (this.state.findOneTime === true) return null; axios({ method: "GET", baseURL: "http://localhost:8000/api/v1/em", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Method": "GET", "Content-Type": "application/json", Accept: "application/json" } }).then(response => { console.log(response); if (response && response.data) { // 直接存储用户数据到state即可,无需手动拼接DOM this.setState({ users: response.data, findOneTime: true, }) } }).catch(error => { console.log(error); }) } render() { return ( <div> <div> <h1 align='center'>用户详情</h1> <table align='center' width='800'> <thead align='center' style={{ fontSize: '20px', color: 'darkorange' }}> <tr align='center'> <td>用户ID</td> <td>姓名</td> <td>密码</td> <td>邮箱</td> <td colSpan='4'>操作</td> </tr> </thead> <tbody id='tableBody' style={{ display: this.state.switchStatus ? 'none' : '' }} align='center'> {/* 遍历state内的用户数据直接渲染表格行 */} {this.state.users.map(item => ( <tr key={item.userId}> <td>{item.userId}</td> <td>{item.userName}</td> <td>{item.userPassword}</td> <td>{item.userEmail}</td> <td colSpan='2'><Button variant='outlined' color='info' onClick={this.allUser}>编辑</Button></td> <td colSpan='2'><Button variant='outlined' color='error' onClick={this.switch}>删除</Button></td> </tr> ))} </tbody> <tfoot> <tr align='center'> <td colSpan='2'><Button variant='outlined' color='info' onClick={this.allUser}>查询</Button></td> <td colSpan='2'><Button variant='outlined' color='error' onClick={this.switch}>切换</Button></td> </tr> </tfoot> </table> </div> </div> ); } }
修改后点击查询按钮获取到用户数据后,React会自动完成表格行渲染,所有Material UI按钮的样式和点击事件都会正常生效。
内容的提问来源于stack exchange,提问作者Iverson860216
相关产品推荐
相关产品推荐

