首页 > 解决方案 > React 不接受 CSS 类

问题描述

我遇到了一个简单的错误,但找不到它。

我创建了一个常量,也为一个元素设置样式。现在我想将常量放入 CSS 中,但不知何故这不起作用。

我想删除这一行:

 <div style={OVERLAY_STYLES}/>

有人可以解释我的错误吗?


const OVERLAY_STYLES = {
  position: "fixed",
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundColor: "rgba(0,0,0, .7)",
  zIndex: 1000,
};



export default function Modal({ open, children, onClick }) {
  const [check, setCheck] = useState([]);

......

  return ReactDOM.createPortal(
    <div className="OVERLAY_STYLES">
    <div style={OVERLAY_STYLES}/>
      <div className="MODAL_STYLES">
        <h1>Blabla.</h1>
        {attribute.map((att, index) => {
          return (
            <div>
              ......
            </div>
          );
        })}
        <div className="b01">
        <button onClick={() => onClick(check)} >Submit</button>
        </div>
      </div>
      </div>
    ,
    document.getElementById("portal")
  );
}

.OVERLAY_STYLES {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0, .7);
  z-index: 1000;
  };


标签: javascriptcssreactjs

解决方案


在反应内联样式中,所有值都需要在 ' ' 内。OVERLAY_STYLES将您的代码更改为:

 .OVERLAY_STYLES {
  position: 'fixed';
  top: '0';
  left: '0';
  right: '0';
  bottom: '0';
  backgroundColor: 'rgba(0,0,0, .7)';
  z-index: '1000';
  };

另外,没有破折号,所以background-color改为backgroundColor


推荐阅读