通过事件处理程序在React中添加CSS类

时间:2019-03-15 08:04:14

标签: javascript css reactjs

我试图像在react文档中提到的那样在鼠标上添加一个CSS类,但是我不确定为什么它不起作用。 请帮助

index.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;
}

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

1 个答案:

答案 0 :(得分:1)

这里的问题是,您正在突变className变量,但这仅不会导致React重新呈现您的组件。

您需要将className存储在状态中,以便在更改它时,React知道重新渲染您的组件。

以下是使用状态的沙盒版本: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");
  }
}}