为什么重新渲染后仍保留样式? [英] Why the styling is kept after re-rendering?

查看:60
本文介绍了为什么重新渲染后仍保留样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 react 并构建了一个简单的程序来生成数组并更改其颜色.我不明白为什么当我生成新数组时会保留前一个数组的颜色.我认为这是因为当我生成一个新数组时状态发生了变化,react 将重新渲染组件并且颜色将设置回默认值.我错过了什么?

这是我的代码:

import React, { useState, useEffect } from 'react';const Dummy2 = () =>{const [arr, setArr] = useState([]);useEffect(() => {生成数组();}, []);const generateArray = () =>{常量温度 = [];for(让我= 1;我< 11;我++){temp.push(i * 2);}setArr(温度);}const changeColor = () =>{const arrayElements = document.getElementsByClassName('array-element');for(let i = 0; i  (<div className="数组元素";键={idx}style={{height: `${value}px`,重量:`${value}px`,边距:'1px 1px',背景颜色:'蓝色'}}></div>))}

<div><button onClick={() =>changeColor()}>更改颜色!</button><button onClick={() =>generateArray()}>new-array</button>

);}导出默认 Dummy2;

我设法通过添加以下功能来解决此问题

const resetColors = () =>{const arrayBars = document.getElementsByClassName('array-element');for(let i = 0; i 

每当数组重置时我都会调用它.

但我仍然不明白为什么要保留样式.

解决方案

这是错误的做法 - 通常,在 React 中,所有可以更改的值都应作为状态处理.并且所有影响组件样式的值都应该作为 props 传递给组件 - 作为一般经验法则,你应该避免像 getElementByIdelement.style = 这样的东西.而是通过 props 传递这些信息.

首先,您可以使用 useState 处理颜色,然后在单击按钮时使用该颜色的 setState.然后可以将颜色值传递到要设置样式的 div 的 style 属性中.

const Dummy2 = () =>{const [arr, setArr] = useState([]);const [color, setColor] = useState("blue");//将颜色初始化为蓝色"/** -- 剪断 -- **/const changeColor = () =>{setColor("红色");//这里设置颜色}返回 (/** -- 剪断 -- **/<div className="数组元素"键={idx}style={{height: `${value}px`,重量:`${value}px`,边距:'1px 1px',backgroundColor: color,//在这里传入颜色}}/** -- 剪断 -- **/<button onClick={() =>changeColor()}>更改颜色!</button>/** -- 剪断 -- **/);}

如果您希望每次生成数组时都重置颜色,那么您可以在 generateArray()<中调用 setColor("<whatever color you want>")/代码> 功能.然后每次生成数组时,颜色将重置为该颜色.

至于为什么样式保持不变,那是因为你每次都生成了相同的数组.React 足够聪明,知道它不需要重新渲染与上次渲染具有完全相同值的组件/div,因此不会调用重新渲染.

I am learning react and built a simple program that generates array and changing it's color. I don't understand why when I generate new array the color of the previous one is kept. I thought that happened because the state has changed when I generated a new array react will re-render the component and the color will be set back to default. What am I missing?

Here is my code:

import React, { useState, useEffect } from 'react';

const Dummy2 = () => {
    const [arr, setArr] = useState([]);

    useEffect(() => {
        generateArray();
    }, []);

    const generateArray = () => {
        const temp = [];
        for(let i = 1; i < 11; i++) {
            temp.push(i * 2);
        }
        setArr(temp);
    }

    const changeColor = () => {
        const arrayElements = document.getElementsByClassName('array-element');
        for(let i = 0; i < arrayElements.length; i++) {
            arrayElements[i].style.backgroundColor = 'red';
        }
    }

    return (
        <div>
            <div className="array-container">
                {arr.map((value, idx) => (
                    <div className="array-element"
                         key={idx}
                         style={{height: `${value}px`,
                                 weight: `${value}px`,
                                 margin: '1px 1px',
                                 backgroundColor: 'blue'}}
                    ></div>))
                }
            </div>
            <div>
                <button onClick={() => changeColor()}>change-color!</button>
                <button onClick={() => generateArray()}>new-array</button>
            </div>
        </div>
    );
}

export default Dummy2;

EDIT: I manage to fix this by adding the following function

const resetColors = () => {
        const arrayBars = document.getElementsByClassName('array-element');
        for(let i = 0; i < arrayBars.length; i++) {
            arrayBars[i].style.backgroundColor = 'blue';
        }
    }

I called it whenever the array is reset.

But still I don't understand why the styling is kept.

解决方案

This is the wrong way to go about doing it - Generally, in react all values that can change should be handled as state. And all values that affect a components styling should be passed as props to a component - As a general rule of thumb, you should avoid things like getElementById and element.style =. Instead pass this information via props.

Firstly, you can handle the color with useState, and then setState of that color when a button is clicked. Then the color value can be passed into the style prop of the div that you want to style.

const Dummy2 = () => {
    const [arr, setArr] = useState([]);
    const [color, setColor] = useState("blue"); // Initialise color to "blue"

    /** -- snip -- **/

    const changeColor = () => {
        setColor("red"); // Set color here
    }

    return (
          /** -- snip -- **/
                    <div className="array-element"
                         key={idx}
                         style={{height: `${value}px`,
                                 weight: `${value}px`,
                                 margin: '1px 1px',
                                 backgroundColor: color, // pass in color here
                          }}
          /** -- snip -- **/
                <button onClick={() => changeColor()}>change-color!</button>
          /** -- snip -- **/
    );
}

If you wish to reset the color each time you generate an array, then you can call setColor("<whatever color you want>") inside of the generateArray() function. Then each time an array is generated, the color will be reset to that color.

As for why the styling is kept the same, it's because you are generating the same array each time. React is smart enough to know that it does not need to re-render a component/div that has the exact same values as the last render and so does not call a re-render.

这篇关于为什么重新渲染后仍保留样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆