【问题标题】:how can i focus only one button at a time and not several at the same time?我怎样才能一次只关注一个按钮而不是同时关注几个?
【发布时间】:2023-03-02 21:22:01
【问题描述】:

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

我的组件是这样的...

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'};

my problem rendered

在父级中是这样渲染的......

tags.forEach((tag) => {
    let saida = <PressedButton onClick={() => handleTag(tag)}>{tag}</PressedButton>

【问题讨论】:

  • 您可以编辑您的答案以显示父组件的代码吗?最有可能的是,您需要将状态提升到您的父组件(呈现 PressedButton 组件的组件,以确保一次只有一个焦点。
  • 我编辑了我的问题!
  • 一会儿,我正在发一个帖子,应该可以帮助到你

标签: javascript css reactjs styles styled-components


【解决方案1】:

您的代码可能看起来像这样来实现您正在寻找的内容:

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>
  );
}

本质上,它所做的是将状态向上移动到父组件。这与反应状态方法一致,如果您有一个需要在按钮之间协调的状态,那么您应该将该状态移动到负责呈现按钮的组件。

【讨论】:

  • 在我的示例中,如果我想在用户再次单击按钮时禁用 PressedIndex,它会是什么样子?
  • 要实现这样的目标,您可能需要稍微更改onClick={() =&gt; {handleTag(tag); setPressedIndex(index)}}。您需要做的是检查索引是否等于当前按下的索引,如果是,则将按下的索引设置为 null 而不是索引。我将把实际代码留给你,因为强化一个简单概念的最好方法就是自己实现它!
【解决方案2】:

我可以提出这样的建议codesandbox

我的想法是存储在状态 id 或按钮的其他标识中,并在点击时推送或删除 id

【讨论】:

  • 谢谢你的回答,尼克,但在你发给我的例子中,按钮也是同时按下的。我一次只需要按下一个
  • 喜欢单选按钮?例如,如果一个按钮处于活动状态,而我按下另一个按钮 - 上一个按钮必须取消选中,对吗?
  • 是的,我认为他们正在寻找单选按钮类型的解决方案
  • @eduardomarr 这里是updated variant。还添加了 2 个功能变体(检查代码 cmets)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多