我怎样才能一次只关注一个按钮而不是同时关注多个按钮?

你能帮我造型吗?我有这些按钮,但一次只能有一个变成蓝色(焦点),而不是同时有几个


我的组件是这样的......


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>


慕标5832272
浏览 118回答 2
2回答

至尊宝的传说

你的代码可能看起来像这样来实现你正在寻找的东西:function parentComponet() {&nbsp; // vvv this was added vvv&nbsp; const [pressedIndex, setPressedIndex] = useState(null);&nbsp; // ... everything else&nbsp; // vvv code was added here too compare to your original code vvv&nbsp; tags.forEach((tag, index) => {&nbsp; &nbsp; let saida = <PressedButton pressed={pressedIndex === index} onClick={() => {handleTag(tag); setPressedIndex(index)}}>{tag}</PressedButton>}然后在孩子身上:function PressedButton({ children, pressed, ...rest }) {&nbsp; // vvv this was removed vvv&nbsp; // const [pressed, setPressed] = useState(false);&nbsp; return (&nbsp; &nbsp; <Container>&nbsp; &nbsp; &nbsp; <Content&nbsp; &nbsp; &nbsp; &nbsp; type="button" {...rest}&nbsp; &nbsp; &nbsp; &nbsp; pressed={pressed}&nbsp; &nbsp; &nbsp; &nbsp; onFocus={() => setPressed(!pressed)}&nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; {children}&nbsp; &nbsp; &nbsp; </Content>&nbsp; &nbsp; </Container>&nbsp; );}本质上,这是在将状态向上移动到父组件。这符合反应状态方法,如果您有一个状态需要在按钮之间进行协调,那么您应该将该状态向上移动到负责呈现按钮的组件。

九州编程

我可以提出类似这样的codesandbox我的想法是存储状态 ID 或按钮的其他标识,并在单击时推送或删除 ID
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript