簡體   English   中英

當我單擊它時,如何防止按鈕觸發另一個按鈕? 反應

[英]How can I prevent the button from triggering the other button when I click it? &React

我的問題是當我單擊我的監視按鈕時,它也會觸發處理程序按鈕。 我怎樣才能防止這種情況?

這是我的按鈕代碼:HTML:


<div className="bot">
                <button id="handler" onClick={() =>{handleClick(0)}}>PICK IT</button>

                <button id="watched" onClick={() =>{watched()}}>I Already Watched This</button>

                <a href={data.trailer} target = "_blank" className = "button">WATCH TRAILER</a>
               

            </div>

反應和 Firebase 部分:

function watched(){
        const db = getDatabase(app);
        update(ref(db,"users/" + userInfo + "/watched/" + data.id),{"watched" : "true"});
    } 

    function handleClick(val){
        if (val >= 250){return 1;}
        const numberOfUsers = 250;
        const randomIndex = Math.floor(Math.random() * numberOfUsers);
        const database = getDatabase(app);
        const watched = ref(database,"users/" + userInfo + "/watched/" + randomIndex);
        onValue(watched,(snapshot) =>{
            if (snapshot.val().watched === "true"){
                handleClick(val+1)
            }
            else{
                const starCountRef = ref(database, 'movies/');
                onValue(starCountRef, (snapshot) => {
                const data = snapshot.val();
                setData(data[randomIndex])
            });}
        })
        

我解決了這樣的問題:

function handleClick(val){
        console.log("handlerrr");
        if (val >= 250){return 1;}
        const numberOfUsers = 250;
        const randomIndex = Math.floor(Math.random() * numberOfUsers);
        const database = getDatabase(app);
        const watched = ref(database,"users/" + userInfo + "/watched/" + randomIndex);
        onValue(watched,(snapshot) =>{
            const val = snapshot.val()  <-------- THIS LINE ADDED
            if (val === "true"){
                handleClick(val+1)
            }
            else{
                const starCountRef = ref(database, 'movies/');
                onValue(starCountRef, (snapshot) => {
                const data = snapshot.val();
                setData(data[randomIndex])
            });}
        })

我不確定,但可能問題是當 onValue 工作之后,我的 handleClick function 正在監聽我的數據庫,並且在我的數據庫每次更新后它都會觸發。 所以我添加了 const val = snapshot.val() 現在它只渲染了 1 次。

只需在 onClick function onClick={(e) =>{handleClick(e, 0)}中添加事件。 添加此事件將防止在沒有實際點擊的情況下觸發按鈕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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