简体   繁体   English

如何使用 onClick 更改容器的背景颜色?

[英]How do I change the background color of the container using onClick?

I am using Next.js.我正在使用 Next.js。 I have a set of colors in a different file.我在不同的文件中有一组 colors。 How do I change it randomly using onClick ?如何使用onClick随机更改它?

The Color.js file Color.js文件

export const Colors = [
    "#16a085",
    "#27ae60",
    "#2c3e50",
    "#f39c12",
    "#e74c3c",
    "#9b59b6",
    "#FB6964",
    "#342224",
    "#472E32",
    "#BDBB99",
    "#77B1A9",
    "#73A857",
];

The Main file主文件

import { Colors } from "./Colors.js";

export default function Home() {
    const randomColor = Math.floor(Math.random() * 12);
    const [color, setColor] = useState(Colors);
    console.log(color);
    const changeColor = () => {       
         setColor(color[randomColor]);   
    };

The Error:错误:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading '9')

You have made 3 mistakes in your code.您在代码中犯了 3 个错误。

First you have created color state with whole color array that you have imported.首先,您使用已导入的整个颜色数组创建了color state。

But instead use one default or empty value as below但改为使用一个默认值或空值,如下所示

const [color, setColor] = React.useState("#16a085");

The next mistake is to you are fetching index from the state color which is not an array once you click on the button it becomes a string and it will index out of bound as no color string has length greater than 7下一个错误是您从 state color中获取索引,一旦您单击按钮,它就会变成一个字符串,并且它会索引超出范围,因为没有颜色字符串的长度大于 7

It can be fixed by它可以通过以下方式修复

setColor(Colors[randomColor]);

Now you will get rid of the error but the color won't change because your random number generator is outside and it is generate when the component updates so fix will be to place it inside the function.现在您将摆脱错误但颜色不会改变,因为您的随机数生成器在外部并且它是在组件更新时生成的,因此修复将其放置在 function 内。

The final code I guess will look as below我猜最终的代码如下所示

import { Colors } from "./Colors";

export default function App() {
  const [color, setColor] = React.useState("#16a085");
  const changeColor = () => {
    const randomColor = Math.floor(Math.random() * 12);
    setColor(Colors[randomColor]);
  };
  return (
    <div className="App">
      <div style={{ color: color }}>hello</div>
      <button onClick={changeColor}>change</button>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM