简体   繁体   English

onclick Reactjs后如何添加class

[英]How to add class after onclick Reactjs

I am working on Reactjs,I have list of questions(using loop) with radio button and i want to add class on radio button which clicked,But right now unable to add class, Here is my current code我正在研究 Reactjs,我有单选按钮的问题列表(使用循环),我想在单击的单选按钮上添加 class,但现在无法添加 class,这是我当前的代码

<FormControlLabel
                    key={`radio${item.id}${count + 2}`}
                    value={item.id.toString()}
                    control={<Radio color="primary" required={item.required} />}
                    label={getChoice(item)}
                    onClick={myfunct}
                  />
                ))}

And in juqery i am using following code在 juqery 中,我使用以下代码

   const myfunct = event => {
         $(this).addClass('my-selected-item');
     }

it is not good idea to change DOM elements directly like this.像这样直接更改 DOM 元素不是一个好主意。 Better store the status of class being added to the element in a state更好地存储 class 的状态被添加到 state 中的元素

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [active, setActive] = useState(false);

  const handler = () => setActive(!active);
  return (
    <div className={active ? "active" : ""} onClick={handler}>
      hello
    </div>
  );
}

just little css to test the presence of class只需一点 css 来测试 class 的存在

.active {
color: red
}

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

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