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

React使用Styled Components时点击修改CSS属性显示模态框的实现问题

//The Exported page
import React, {useState} from "react";
import styled from "styled-components";

export function InfoCalon(){
  // 声明控制模态框显隐的状态
  const [showModal, setShowModal] = useState(false);

  return(
    <CustomStyle>
    <div className="content-container">
        {/* 绑定点击事件修改状态 */}
        <button id="button1" className="button" onClick={() => setShowModal(true)}>Button 1</button>
    </div>

    {/* 动态绑定display属性,状态为true时显示模态框 */}
    <div id="modal" className="modalpopup" style={{display: showModal ? 'block' : 'none'}}>
        <div className="modal-content">
            //Modal Contents
            {/* 可额外添加关闭按钮 */}
            <button className="button" onClick={() => setShowModal(false)}>关闭模态框</button>
        </div>
    </div>
    </CustomStyle>
  )
}

const CustomStyle = styled.div`
background-color: black;
color: white;

.button {
  border: none;
  min-width: 30%;
  height: auto;
  display: inline-flexbox;
  text-align: center;
  text-decoration: none;
  margin: 10px 10% 10px 10%;
  transition-duration: 0.2s;
  cursor: pointer;
}


.button:hover{
  transform: scale(1.02);
}

.button:active{
  transform: scale(0.97);
  transition-duration: 0.05s;
}

.modalpopup {
  display: none;
  position: fixed;
  z-index: 10;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #102037;
  margin: 7% auto;
  position: relative;
  padding: 1% 3% 3% 3%;
  width: 80%;
}
` 

核心修改点

  1. 放弃原生DOM操作的写法,改用React状态驱动UI变化:通过useState声明showModal状态,初始值为false对应模态框默认隐藏的状态,避免直接查找DOM节点出现的null报错。
  2. 按钮绑定onClick事件,点击时将showModal状态修改为true,触发组件重渲染。
  3. 模态框节点通过行内style动态绑定display属性,当showModal为true时覆盖styled-components中默认的display: none为display: block,实现模态框显示。
  4. 修正JSX语法问题:原生HTML的class属性在JSX中需要写为className,否则样式不会正常生效。

如果需要实现点击模态框外部关闭的功能,可以给modalpopup节点添加点击事件,判断点击源为模态框背景时将showModal设为false即可。

内容的提问来源于stack exchange,提问作者Giga Hidjrika A A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:45:04