亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我怎樣才能一次只關注一個按鈕而不是同時關注多個按鈕?

我怎樣才能一次只關注一個按鈕而不是同時關注多個按鈕?

慕標5832272 2023-05-11 10:20:25
你能幫我造型嗎?我有這些按鈕,但一次只能有一個變成藍色(焦點),而不是同時有幾個我的組件是這樣的......import { Container, Content } from './styles';function PressedButton({ children, ...rest }) {  const [pressed, setPressed] = useState(false);  return (    <Container>      <Content        type="button" {...rest}        pressed={pressed}        onFocus={() => setPressed(!pressed)}        >      {children}      </Content>    </Container>  );}PressedButton 的樣式...import styled from 'styled-components';(...)export const Content = styled.button`  (...)  //props  background: ${({ pressed })  => pressed ? `linear-gradient(#449fd8, #1b699a)`: '#2a2a2a'};  color: ${({ pressed })  => pressed ? '#fff': '#7d7d7d'};我的問題呈現在父母中是這樣呈現的......tags.forEach((tag) => {    let saida = <PressedButton onClick={() => handleTag(tag)}>{tag}</PressedButton>
查看完整描述

2 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

你的代碼可能看起來像這樣來實現你正在尋找的東西:


function parentComponet() {

  // vvv this was added vvv

  const [pressedIndex, setPressedIndex] = useState(null);

  // ... everything else

  // vvv code was added here too compare to your original code vvv

  tags.forEach((tag, index) => {

    let saida = <PressedButton pressed={pressedIndex === index} onClick={() => {handleTag(tag); setPressedIndex(index)}}>{tag}</PressedButton>

}

然后在孩子身上:


function PressedButton({ children, pressed, ...rest }) {

  // vvv this was removed vvv

  // const [pressed, setPressed] = useState(false);


  return (

    <Container>

      <Content

        type="button" {...rest}

        pressed={pressed}

        onFocus={() => setPressed(!pressed)}

        >

      {children}

      </Content>

    </Container>

  );

}

本質上,這是在將狀態向上移動到父組件。這符合反應狀態方法,如果您有一個狀態需要在按鈕之間進行協調,那么您應該將該狀態向上移動到負責呈現按鈕的組件。


查看完整回答
反對 回復 2023-05-11
?
九州編程

TA貢獻1785條經驗 獲得超4個贊

我可以提出類似這樣的codesandbox

我的想法是存儲狀態 ID 或按鈕的其他標識,并在單擊時推送或刪除 ID


查看完整回答
反對 回復 2023-05-11
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號