[英]Toggle Button in React not Toggling
I am working on a react app that has a toggle button.我正在开发一个带有切换按钮的反应应用程序。 I have a component that contains the the basic outline of the toggle button.
我有一个包含切换按钮基本轮廓的组件。 I can make the toggle button work in regular HTML with CSS.
我可以使用 CSS 使切换按钮在常规 HTML 中工作。 I am trying to do the same thing in my react.
我试图在我的反应中做同样的事情。 Create a toggle button with jsx and css.
使用 jsx 和 css 创建一个切换按钮。
Is this possible?这可能吗? If not should use a useState hook, how can I set that up.
如果不应该使用 useState 钩子,我该如何设置它。
Component零件
ToggleBtn.js 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 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);
}
I was able to get this to work.我能够让它工作。 I created the component (toggle button) in its own file with a CSS file to style it on its own and made it work.
我使用 CSS 文件在自己的文件中创建了组件(切换按钮),以自行设置样式并使其工作。
This is the code used.这是使用的代码。
Switch.js开关.js
import React from 'react';从“反应”导入反应; import "./Switch.css";
导入“./Switch.css”;
const Switch = () => {
return (
<label className="switch1">
<input type="checkbox"/>
<span className="slider1"/>
</label>
);
}
export default Switch ;
Switch.css开关.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;
}
I then imported the component in my original toggle file.然后我将组件导入到我原来的切换文件中。
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.