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%; } `
核心修改点
- 放弃原生DOM操作的写法,改用React状态驱动UI变化:通过
useState声明showModal状态,初始值为false对应模态框默认隐藏的状态,避免直接查找DOM节点出现的null报错。 - 按钮绑定
onClick事件,点击时将showModal状态修改为true,触发组件重渲染。 - 模态框节点通过行内style动态绑定
display属性,当showModal为true时覆盖styled-components中默认的display: none为display: block,实现模态框显示。 - 修正JSX语法问题:原生HTML的
class属性在JSX中需要写为className,否则样式不会正常生效。
如果需要实现点击模态框外部关闭的功能,可以给modalpopup节点添加点击事件,判断点击源为模态框背景时将showModal设为false即可。
内容的提问来源于stack exchange,提问作者Giga Hidjrika A A
相关产品推荐
相关产品推荐

