简体   繁体   English

通过事件处理程序在 React 中添加一个 css 类

[英]Adding a css class in React through event handlers

I was trying to add a css class on mouse over just as mentioned in the react documentation but I am not sure why it is not working.正如反应文档中提到的那样,我试图在鼠标悬停时添加一个 css 类,但我不确定为什么它不起作用。 Please help请帮忙

index.js:索引.js:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  let className = "";
  return (
    <div className="App">
      <h1
        className={className}
        onMouseOver={() => {
          if (!className.includes("colorRed")) {
            className += " colorRed";
          }
        }}
      >
        Hello CodeSandbox
      </h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

style.css样式文件

.App {
  font-family: sans-serif;
  text-align: center;
}

.colorRed{
  color:red;
}

Link: https://codesandbox.io/s/xjx72w5kkw?fontsize=14链接: https : //codesandbox.io/s/xjx72w5kkw?fontsize=14

This issue here is that you're mutating the className variable but this alone doesn't cause React to re-render your component.这里的问题是您正在改变className变量,但这本身并不会导致 React 重新渲染您的组件。

You'll need to store the className in the state so that when you change it, React knows to re-render your component.您需要将className存储在 state 中,以便在您更改它时,React 知道重新渲染您的组件。

Here's a version of your sandbox making use of state: https://codesandbox.io/s/m51qoq72pp这是使用状态的沙箱版本: https : //codesandbox.io/s/m51qoq72pp

// First we're importing useState from react
// This is part of the new Hooks mechanism 
// More about hooks: https://reactjs.org/docs/hooks-intro.html
// You could also use a class and this.setState instead
import React, { useState } from "react";

// Then we set up our piece of state
const [className, setClassName] = useState("");

// Your event now uses setState
onMouseOver={() => {
  if (!className.includes("colorRed")) {
   setClassName(current => current + " colorRed");
  }
}}

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

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