[英]Toggle Button in React not Toggling
我正在开发一个带有切换按钮的反应应用程序。 我有一个包含切换按钮基本轮廓的组件。 我可以使用 CSS 使切换按钮在常规 HTML 中工作。 我试图在我的反应中做同样的事情。 使用 jsx 和 css 创建一个切换按钮。
这可能吗? 如果不应该使用 useState 钩子,我该如何设置它。
零件
ToggleBtn.js
const ToggleBtn = () => {
return (
<div class="space-around">
<h3 className="h3">Annually</h3>
<label className="switch">
<input type="checkbox" checked/>
<span className="slider"></span>
</label>
<h3 className="h3">Monthly</h3>
</div>
);
}
app.css
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
margin: 0 10px;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: 0.4s;
border-radius: 34px;
}
.switch input {
display: none;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: -20px;
bottom: 4px;
background-color: white;
transition: 0.4s;
border-radius: 50px;
}
input:checked + .slider {
background-color: var(--Purplish);
}
input:checked + .slider:before {
transform: translateX(50px);
}
我能够让它工作。 我使用 CSS 文件在自己的文件中创建了组件(切换按钮),以自行设置样式并使其工作。
这是使用的代码。
开关.js
从“反应”导入反应; 导入“./Switch.css”;
const Switch = () => {
return (
<label className="switch1">
<input type="checkbox"/>
<span className="slider1"/>
</label>
);
}
export default Switch ;
开关.css
.switch1 {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch1 input {
opacity: 0;
width: 0;
height: 0;
}
.slider1 {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
border-radius: 50px;
}
.slider1::before {
position: absolute;
content: "";
height: 26px;
width: 26px;
bottom: 4px;
left: 4px;
background-color: white;
transition: 0.4s;
border-radius: 50px;
}
input:checked + .slider1::before {
transform: translateX(26px);
}
input:checked + .slider1 {
background-color: #2196f3;
}
然后我将组件导入到我原来的切换文件中。
import Switch from "./components/Switch";
const ToggleBtn = () => {
return (
<div class="space-around">
<h3 className="h3">Annually</h3>
<Switch />
<h3 className="h3">Monthly</h3>
</div>
);
}
export default ToggleBtn;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.