我有一些按钮,我正在尝试为单击的按钮添加active
类。但是,当我单击其中一个按钮时,所有按钮都处于活动状态。
const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");
const Button = ({ message }) => {
const [condition, setCondition] = useState(false);
return (
<div>
{
Object.keys(res).map((data) => (
<Button className={condition ? "button toggled" : "button"} onClick=.
{() => {
setCondition(!condition)}
}}
))
}
</div>
);
//Updated
Object.keys(res).map((data) => (
<Button className={condition ? "button toggled" : "button"} onClick=.
{() => {
setCondition(condition === "off" ? "on" : "off")}
}}
))
}
</div>
); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);
如果我单击第一个按钮,这是可行的,但是如果我再次单击相同的按钮,则应删除此活动的类
答案 0 :(得分:2)
import React, {useState, useCallback} from "react";
const defaultButtons = [
{id: 1},
{id: 2},
{id: 3},
{id: 4}
];
export default function App() {
const [toggledButtonId, setToggledButtonId] = useState(false);
function toggleButton(button) {
setToggledButtonId(button.id);
}
const toggleButton = useCallback((id) => setToggledButtonId(state => id), [toggledButtonId]);
return (
<div>
{defaultButtons.map(button => {
const isToggled = button.id === toggledButtonId;
return (
<button
key={button.id}
className={isToggled ? "toggledButtonId toggled" : "toggledButtonId"}
onClick={toggleButton(button.id)}>
{String(isToggled)}
</button>
)
})}
</div>
)
}
答案 1 :(得分:0)
您需要为每个按钮使用单独的状态处理程序:
const Button = ({ message }) => {
const [condition, setCondition] = useState(false);
const [condition2, setCondition2] = useState(false);
return (
<div>
<div
onClick={() => setCondition(!condition)}
className={condition ? "button toggled" : "button"}
>
{message}
</div>
<div
onClick={() => setCondition(!condition2)}
className={condition2 ? "button toggled" : "button"}
>
{message}
</div>
</div>
);
};
render(<Button message="Click me if you dare!" />, node);
答案 2 :(得分:0)
这是一个非常幼稚的解决方案,但是它将帮助您理解问题。
如果您在实际项目中,建议您使用现有的库(可以通过搜索react toggle button group
找到)
import React, {useState} from "react";
const defaultButtons = [
{id: 1},
{id: 2},
{id: 3},
{id: 4}
];
export default function App() {
const [toggledButtonId, setToggledButtonId] = useState(null);
function toggleButton(button) {
setToggledButtonId(button.id);
}
return (
<div>
{defaultButtons.map(button => {
const isToggled = button.id === toggledButtonId;
return (
<button
key={button.id}
className={isToggled ? "toggledButtonId toggled" : "toggledButtonId"}
onClick={() => toggleButton(button)}>
{String(isToggled)}
</button>
)
})}
</div>
)
}
答案 3 :(得分:0)
也许您想检查一下。
https://codesandbox.io/embed/import-css-file-react-vs488?fontsize=14&hidenavigation=1&theme=dark
答案 4 :(得分:0)
您可以使用内部状态创建组件Button,然后使用此组件填充按钮。也许您可以使用:active CSS选择器并完全避免使用js