簡體   English   中英

切換按鈕突出顯示

[英]Toggle button highlight

我正在嘗試打開和關閉按鈕的背景顏色,包括隨后按下另一個按鈕時。 目前,我能夠通過以下方式實現這一目標:

const [isActive, setIsActive] = useState(false);

  const handleClick = () => {
    setIsActive(current => !current);
  };

  return (
    <View>
      <Pressable
        style={{
          backgroundColor: isActive ? 'orange' : 'white',
        }}
        onClick={handleClick}
      >
        <Text style={{color: isActive ? 'white' : 'black'}}>Hello world</Text>
      </Pressable>
    </View>
  );
}

但我遇到的問題是,當我單擊一個按鈕時,它們都會響應,更改所有背景和字體 colors,然后再次單擊會將它們全部還原。 我如何更改它以僅突出顯示所選按鈕,然后在選擇另一個按鈕時關閉?

謝謝!

你必須做這樣的事情:

    const [buttonState, setButtonState] = useState({})

    .....


    const toggleButton = (id) => {
        if(buttonState[id]){
            const state = buttonState
            delete state[id]
            setButtonState(state)
        }else{
            const state = buttonState
            state[id] = true
            setButtonState(state)
        }
    }

    .......
    
    return(
        .......
        <Pressable
          style={{
            backgroundColor: buttonState[id]? 'orange' : 'white',
          }}
          onClick={()=> handleClick(id)}
        >
            <Text style={{color: buttonState[id] ? 'white' : 'black'}}>Hello world</Text>
        </Pressable>
    )

其中id是按鈕的 id。

或者

你可以使用useRef

所有按鈕都響應相同的 state 值,因此這是預期的。 為每個按鈕創建一個 state 值,或者創建一個包含 state 值的 Button 組件。

暫無
暫無

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

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