[英]ReactJS onclick add or remove class to another element
I am struggling to convert my normal jQuery code in to React JS (I'm new to React).我正在努力将我的正常 jQuery 代码转换为 React JS(我是 React 的新手)。
I have the following code:我有以下代码:
$(".add").click(function () { $("nav").addClass("show"); }); $(".remove").click(function () { $("nav").removeClass("show"); }); $(".toggle").click(function () { $("nav").toggleClass("show"); });
nav { width: 250px; height: 150px; background: #eee; padding: 15px; margin-top: 15px; } nav.show { background: red; color: white; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <button class="add">Add</button> <button class="remove">Remove</button> <button class="toggle">Toggle</button> <nav>Navigation menu</nav>
Tried references seems that only add/remove class for the same element:尝试过的参考似乎只为同一元素添加/删除 class:
https://stackoverflow.com/a/42630743/6191987 https://stackoverflow.com/a/42630743/6191987
How to add or remove a className on event in ReactJS?如何在 ReactJS 事件中添加或删除类名?
So, how can I convert or create the same jQuery methods to ReactJS?那么,如何将相同的 jQuery 方法转换或创建为 ReactJS?
You could check this sandbox link for implementation您可以检查此 沙箱链接以进行实施
function App() {
const [show, setShow] = React.useState();
return (
<div className="App">
<button className="add" onClick={() => setShow(true)}>
Add
</button>
<button className="remove" onClick={() => setShow(false)}>
Remove
</button>
<button className="toggle" onClick={() => setShow(!show)}>
Toggle
</button>
<nav className={show ? "show" : ""}>Navigation menu</nav>
</div>
);
}
You could combine the use useRef
for nav
and manipulate the ref (accessing nav
's DOM) with event handlers for each button您可以将useRef
用于nav
并将 ref (访问nav
的 DOM)与每个按钮的事件处理程序结合使用
import React from "react";
import "./styles.css";
export default function App() {
const navRef = React.useRef(null);
const onAddClick = (e) => {
navRef.current.classList.add("show");
};
const onRemoveClick = (e) => {
navRef.current.classList.remove("show");
};
const onToggleClick = (e) => {
navRef.current.classList.toggle("show");
};
return (
<div className="App">
<button onClick={onAddClick}>Add</button>
<button onClick={onRemoveClick}>Remove</button>
<button onClick={onToggleClick}>Toggle</button>
<nav ref={navRef}>Navigation menu</nav>
</div>
);
}
.App {
font-family: sans-serif;
}
nav {
width: 250px;
height: 150px;
background: #eee;
padding: 15px;
margin-top: 15px;
}
nav.show {
background: red;
color: white;
}
Codesanbox link for demo用于演示的 Codesanbox 链接
Reference:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.