簡體   English   中英

React 中的切換按鈕不切換

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM