我正在嘗試在 Next.Js 中進行開關。為了獲得幫助,我觀看了此視頻:https : //www.youtube.com/watch?v= 1W3mAtAT7os&t = 740s 問題是,每次我重新加載頁面時,開關需要在移動開關之前單擊 2 次,然后單擊 3 次才能將其關閉
這是我的 .js 檔案中的代碼
import React, { useEffect, useState } from 'react'
export default function Navigation() {
const [menuActive, setMenuActive] = useState(false);
const Toggle = ({onChange}) =>
<label className='menu-button'>
<input type="checkbox" onChange={onChange} className='input'/>
<span className='slider'/>
</label>
;
return (
<div>
<div className='menu-button-container'>
<Toggle onChange={(event) => setMenuActive(event.target.checked)} />
</div>
</div>
)
}
這是CSS:
.menu-button-container {
width: 50%;
height: 125px;
right: 0;
display: flex;
justify-content: flex-end;
align-items: center;
position: fixed;
}
.menu-button {
position: relative;
width: 90px;
display: flex;
justify-content: center;
}
.input {
position: absolute;
left: -9999px;
top: -9999px;
}
.input:checked .slider:before {
width: 17px;
height: 17px;
border-radius: 50px;
transition: 0.3s;
background: white;
background-repeat: no-repeat;
background-size: 12.5px;
background-position: center;
left: 30px;
content: "";
}
.slider {
display: flex;
cursor: pointer;
width: 50px;
height: 25px;
border-radius: 100px;
background-color: black;
position: relative;
align-items: center;
z-index: 2;
}
.slider:before {
content: "";
position: absolute;
left: 2px;
width: 17px;
height: 17px;
border-radius: 50px;
transition: 0.3s;
background: white;
background-repeat: no-repeat;
background-size: 12.5px;
background-position: center;
}
提前致謝 :)
uj5u.com熱心網友回復:
您忘記在Toogle組件中傳遞復選框值!
試試這個代碼它的作業!
import React, { useEffect, useState } from 'react'
export default function Navigation() {
const [menuActive, setMenuActive] = useState(false);
const Toggle = ({ onChange, value }) =>
<label className='menu-button'>
<input checked={value} type="checkbox" onChange={onChange} className='input' />
<span className='slider' />
</label>
;
return (
<div>
<div className='menu-button-container'>
<Toggle value={menuActive} onChange={(event) => setMenuActive(event.target.checked)} />
</div>
</div>
)
}
uj5u.com熱心網友回復:
嘗試使用真值而不是假值。
import React, { useEffect, useState } from 'react'
export default function Navigation() {
const [menuActive, setMenuActive] = useState(true);
const Toggle = ({onChange}) =>
<label className='menu-button'>
<input type="checkbox" onChange={onChange} className='input'/>
<span className='slider'/>
</label>
;
return (
<div>
<div className='menu-button-container'>
<Toggle onChange={(event) => setMenuActive(event.target.checked)} />
</div>
</div>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/409777.html
標籤:
上一篇:如何最好地在Javascript陣列中搜索部分匹配項?
下一篇:將日期數字轉換為波斯數字
