import React ,{useState}from 'react';import './App.css';function App() { const password =[2,2,3]; const [digits ,setDigits]=useState([0,0,0]); const [isUnlocked,setIsUnlocked]=useState(false); let setDigitAtIndex=(digit,idx)=>{ setDigits((currentDigits)=> [ ...currentDigits.slice(0, idx), digit, ...currentDigits.slice(idx + 1) ] ); }; let checkPassword=() =>{ for (let i=0;i<password.length;i++){ if(password[i]===digits[i]){ return; } } setIsUnlocked(true); } return ( <section> <h1>Passo</h1> <div style={{display:'flex'}}> <input type="number" value={digits[0]} onChange={(event) => setDigitAtIndex(parseInt(event.target.value),0)}/> <input type="number" value={digits[1]} onChange={(event)=>setDigitAtIndex(parseInt(event.target.value),1)}/> <input type="number" value={ digits[2]} onChange={(event)=>setDigitAtIndex(parseInt(event.target.value),2)}/> </div> <button onClick={()=>checkPassword()}>Press Me</button> { isUnlocked && <p>Unlocked</p>} </section> );}export default App;在反應中運行此應用程序后,當我單擊帶有 0 0 0 的按我按鈕時,它顯示已解鎖,但在輸入 2 2 3 后它不起作用,但在輸入 223 后應該可以工作需要幫助嗎?以及任何正在學習反應的人那些可以回答這個問題
1 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
let setDigitAtIndex=(digit,idx)=>{
let temp = [...digits];
temp[idx] = digit;
setDigits(temp);
};
這看起來容易多了?
您的檢查密碼功能也不正確。
替換===為!==
let checkPassword=() =>{
for (let i=0;i<password.length;i++){
if(password[i]!==digits[i]){
setIsUnlocked(false); // if the password is wrong, it will hide the text again
return;
}
}
setIsUnlocked(true);
}
- 1 回答
- 0 關注
- 150 瀏覽
添加回答
舉報
0/150
提交
取消