React-toggle类:useState钩子形式的几个按钮



我有一些按钮,我正在尝试为单击的按钮添加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);

如果我点击第一个按钮,这是有效的,但如果我再次点击相同的按钮,这个活动类应该被删除

这里有一个非常简单的解决方案,但它将帮助您理解问题。

如果你在一个真正的项目中,我建议你使用现有的库(可以通过搜索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>
)
}

您需要为每个按钮使用一个单独的状态处理程序:

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);

也许您想检查一下。

https://codesandbox.io/embed/import-css-file-react-vs488?fontsize=14&隐藏导航=1&主题=深色

您可以在中创建状态为的组件Button,并使用该组件填充按钮。也许你可以使用:activeCSS选择器,并避免js在所有

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>
)
}

最新更新