【问题标题】:Having problem in changing css using useState in react在 react 中使用 useState 更改 css 时遇到问题
【发布时间】:2022-02-09 20:11:59
【问题描述】:

我正在尝试构建一个响应模式。打开时,背景或主体颜色必须更改为较暗的颜色,并且模式应该打开,关闭时,一切都必须恢复正常。 我试图通过这种方法来实现这一点:

const [modalState, setModalState] = useState(false);
const [modalBg, setModalbg] = useState(false);

function handleClick() {
    setModalState(true);
    setModalbg(true);
    
}
return (
  {
      !modalState ?
       null
       : <Modal modalState = {setModalState}/>
  }
  {
      !modalBg ?
       document.body.style.backgoundColor = "ffff"
      : document.body.style.backgoundColor = 'rgba(39, 38, 38, 0.616)'
  }
  <button onClick= {handleClick}>Open</button>
  
)

问题是,它不会改变正文的颜色,而是将文本呈现到页面上,如“#fff”或“红色”。我不知道为什么会这样,有人可以帮忙吗?

谢谢!

【问题讨论】:

    标签: javascript node.js reactjs react-state


    【解决方案1】:

    您的方式并不是真正的“反应”方式来处理模态。首先,在创建模式时,我对门户的使用再怎么强调也不为过。请查看this 以真正了解门户是什么以及它们如何为您提供帮助。
    继续前进,您可以创建一个模态组件,如下所示,并使用状态触发此组件。只要确保将该状态的设置器作为道具传递给组件,在我的情况下为setShowModal
    您的模态背景包含在 div my-modal-container 中,您可以随意更改它。

    import React, { useState, useEffect } from 'react';
    import ReactDOM from 'react-dom';
    
    const MyModal = ({setShowModal}) => {
    
        const handleClose = () => {
            setShowModal(false)
        };
    
        return ReactDOM.createPortal(
            <div className='my-modal-container'>
                <div class='my-modal-body'>
                    //Place all you modal body here
                </div>
            </div>,
            document.getElementById('portal')
        );
    };
    export default MyModal;
    

    如果您选择使用上述门户,请确保在您的 index.html 文件中的&lt;div id="root"&gt;&lt;/div&gt; 正下方添加&lt;div id="portal"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      您不应该在返回函数中设置正文的背景颜色。这意味着返回 JSX。

      尝试使用 useEffect 钩子,例如:

      useEffect(() => {
        if (modalBg) {
          document.body.style.backgoundColor = "rgba(39, 38, 38, 0.616)";
        } else {
          document.body.style.backgoundColor = "ffff";
        }
      }, [modalBg]);
      

      【讨论】:

        猜你喜欢
        • 2023-02-05
        • 2020-09-02
        • 2019-12-05
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多