简体   繁体   English

同时删除并更改多个元素的 className onClick - ReactJS

[英]Remove and change className onClick for multiple elements simultaneously - ReactJS

I am currently trying to display several buttons based on array values.我目前正在尝试根据数组值显示几个按钮。 Out of those buttons, one will have a different className to the others and I want to switch this className to the button that's clicked.在这些按钮中,一个将具有与其他按钮不同的className ,我想将此 className 切换为单击的按钮。

In my codesandbox example, "John" has className value of "one".在我的代码框示例中,“John”的 className 值为“one”。 I want to be able to click on another button, giving it the className of "one" and giving John (or any other element that had the initial className of one) className="two"我希望能够单击另一个按钮,给它“一”的类名并给约翰(或任何其他初始类名为一的元素)className =“二”

Here's a codesandbox , hopefully that makes more sense.这是一个代码框,希望这更有意义。

If you mean you want the button you click on to turn red, here is a codesandbox with this functionality added:如果你的意思是你想让你点击的按钮变成红色,这里是一个添加了这个功能的代码框:

https://codesandbox.io/s/frosty-herschel-l87wx https://codesandbox.io/s/frosty-herschel-l87wx

create a state:创建一个 state:

const [activeName, setActiveName] = useState("");

then when someone CLICK the element put onClick event:然后当有人点击元素放置 onClick 事件:

onClick={() => setActiveName("invest")}

Now set up a Class Rule, if activeName === 'invest' && 'classYouWantToApply'现在设置一个 Class 规则,如果 activeName === 'invest' && 'classYouWantToApply'

like this:像这样:

<div className={`${activeName === "invest" && "active"}`}>Invest</div>

So here if my State matches the 'invest' which is the name of the element, then class 'active' applies, if the state does NOT match, then nothing happens.所以在这里,如果我的 State 与元素名称“投资”匹配,则 class“活动”适用,如果 state 不匹配,则什么也不会发生。

This way ONLY 1 element that matches the state will have applied class, the rest will not.这样,只有一个与 state 匹配的元素将应用 class,rest 不会。

I am assuming you are doing this for a NAV BAR, so that when user clicks a NAV Element, it lights up, so user can see in Which Nav Element he is browsing.我假设您正在为 NAV BAR 执行此操作,因此当用户单击 NAV 元素时,它会亮起,因此用户可以看到他正在浏览哪个 Nav 元素。 So this is the solution.所以这就是解决方案。

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

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