javascript - 在 React 的 render 方法中设置 CSS 变量是个好习惯吗?

标签 javascript html css reactjs css-variables

我昨天创建了一个帖子,但错误地删除了它 我必须创建一个具有特定样式的组件。问题在于,ComponentDidMount() 方法在渲染组件时会产生一些闪烁现象。现在是 CSS 设置的时间了。

我认为我的组件对资源要求很高,因此 componentDidMount() 发生时会出现一两帧的滞后。这就是为什么我在这里只提供一个片段而不是完整的演示,我的小演示可以很好地实现零特定闪烁。

然后我在渲染方法中输入了值。就像下面这样:

componentDidMount(){
   // the CSS rendering will lag by releasing a flickering :/
}

render(){

    // awesome, by setting my style in the render the good style is returned instantly.

    if (Math.round(window.scrollY + window.innerHeight +50) >= Math.round(document.body.scrollHeight)) {

            document.documentElement.style.setProperty('--background-transition', "")
            document.documentElement.style.setProperty('--is-page-bottom', "orange");
            document.documentElement.style.setProperty('--background-transition', "all 0.3s ease-out")
         }
             else{
                //setIsPageBottom_CSSVariable("rgba(84, 80, 79,0.85)")
                document.documentElement.style.setProperty('--background-transition', "")
                document.documentElement.style.setProperty('--is-page-bottom', "purple");
                document.documentElement.style.setProperty('--background-transition', "all 0.3s ease-out")
             }

昨天有人告诉我,我应该使用react React Hook来管理这种情况,或者使用componentDidMount,但是在我的情况下,componentDidMount失败了,因为在安装相关背景颜色之前会闪烁。

我是React Hook的新手,所以如果我理解得很好,我可以直接在useEffect中制作类似document.documentElement.style.setProperty的东西,它会与React Hook的设计保持一致吗?

同时我发现我的解决方案很好,因为 when reading the official React's documentation, it is noted that :

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.

好吧,如果我能够以清晰的方式思考我的组件,那么这样做绝不是一件坏事,不是吗?只是不是我认为的最佳实践。 有人建议我使用 addeventlistener,但这里它是关于在第一个渲染组件的循环上立即渲染我的样式。因此,addeventlistener 是针对与我所遇到的不同情况的一种解决方案。

在所有情况下,您建议使用哪种替代方案来避免在 componentDidMount() 中插入 CSS 设置时出现闪烁?与 React hook 有什么联系?

最佳答案

这是使用 useEffect 的方式

//componentDidMount replacement
useEffect(() => {
 //your code goes here
}, [])

关于javascript - 在 React 的 render 方法中设置 CSS 变量是个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61013675/

相关文章:

javascript - 将 2 个相关数组映射在一起

javascript - 如何动态地将div的高度设置为屏幕的高度,直到滚动条到达屏幕底部

javascript - 在 NodeJS 子进程中执行任意 JavaScript 代码(不是命令)

javascript - 替换 div 内容 ajax bootstrap

javascript - svg 上的 Bootstrap 弹出窗口

html - % 行高问题

javascript - Jquery - 隐藏单选按钮 - 但使图像可点击以显示更大的图像

PHP 在单独的代码块中显示动态填充的变量

javascript - 获取一行 jQuery 的最后一个 li

html - 位于导航和标题顶部的 Logo