【问题标题】:Reactjs hooks set active buttonsReactjs 钩子设置活动按钮
【发布时间】:2020-05-16 11:10:55
【问题描述】:

我的后端有这个按钮

const ShiftCalendar = btn => {
  console.log('btn ->', btn);
};
btnList.map((btn,i) => {
        const is_active = btn.is_default ? 'is_active' : '';
        return (
          <Button
            key={i}
            variant="dark mt-3 mr-3 "
            className={is_active}
            size="sm"
            onClick={() => ShiftCalendar(btn)}
          >
            {btn.title}
          </Button>
        );
})

如何通过 onclick 事件更改活动按钮?

如您所见,我的按钮 1 有一个 is_active 类,我想要的是通过单击按钮来更改活动状态。如果我单击按钮 2,按钮 1 将不再具有 is_active 类,而按钮 2 将具有 is_active 类

Check button image here

顺便说一句,我使用的是钩子而不是组件。

谢谢

【问题讨论】:

  • 您想使用 is_active 值禁用和启用按钮???
  • 您能否详细说明您想要什么?
  • 问题已更新。请检查谢谢

标签: reactjs react-hooks


【解决方案1】:

这样想。当我们点击一​​个按钮时,我们想记住点击了哪个按钮,然后当我们重新渲染页面时,让我们将最后点击的按钮标记为活动的,其他的则不活动。

所以要在 React 中做到这一点,你要做的是:

  1. 首先从按钮数组(来自 API、props 或某些常量)中获取 isDefault 按钮,并将其作为默认值存储在您的状态中以进行第一次渲染。如果您没有此键 isDefault,您可以通过不激活任何按钮或激活第一个按钮来优雅地跳过此步骤,以最适合您的用例为准。
  2. onClick 的一个按钮,调用一个函数,你应该把点击的 buttonId 保存在 state 中。
  3. 然后在下一次渲染中,通过将 buttonId 与您在状态中存储的内容进行比较来确定哪个按钮处于活动状态。如果匹配,则 className 应该是活动的,否则你想要的任何其他类名。
import React, { useState } from 'react';

const btnList = [
    {
        id: 1,
        title: 'Button 1',
        isDefault: true,
    },
    {
        id: 2,
        title: 'Button 2',
        isDefault: false,
    }
];

const ButtonList = props => {
    // 1. Get the default so we could set it in the state
    const [defaultBtn] = btnList.some(btn => btn.isDefault === true);

    const [activeButtonId, setActiveButtonId] = useState(defaultBtn ? defaultBtn.id : null);

    // 2. Create an event handler so when we click on a button we save the buttonId in state
    const handleButtonClick = event => {
        setActiveButtonId(Number(event.target.value));
    };

    return (
        <div>
            {btnList.map(btn => (
                <Button
                    key={btn.id}
                    variant="dark mt-3 mr-3 "
                    className={btn.id === activeButtonId ? 'is_active' : ''}// Compare the button's id to what we have in state to determine which should be active
                    size="sm"
                    value={btn.id} // Set the value of the button as the button's id
                    onClick={handleButtonClick}
                >
                    {btn.title}
                </Button>
            ))}
        </div>
    )
}

export default ButtonList;

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2021-02-03
    • 2018-07-08
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多