【问题标题】:Toggle switch in reactjsreactjs中的切换开关
【发布时间】:2021-02-02 10:19:42
【问题描述】:

当我禁用第二个按钮时,我启用了第一个按钮。这工作但不正常。 我需要双击第二个按钮以启用第二个按钮并禁用第一个按钮。 我做了很多调试和搜索,但我没有找到我哪里出错了。任何形式的帮助将不胜感激。提前致谢!

反应js代码

import React, {useState} from 'react'
import {Link as LinkR} from 'react-router-dom'
import './SectionConnect.css'

const SectionConnect = () => {
  return (
    <div className="connect-container">
      <div className="connect-wrapper">
        <h2>How it works</h2>
        <p>We connect you with the very best practitioners and most effective methods to achieve optimal health.</p>
        <div className="connect-btn">
          <LinkR to='/' onClick={()=>setClick(true)} className={clicked ? 'active-btn':'disable-btn'}>
            For companies
          </LinkR>
          <LinkR to='/forIndividuals' onClick={()=>setClick(!clicked)} className={clicked ? 'disable-btn':'active-btn'}>
            For individuals
          </LinkR>
        </div>
      </div>
    </div>
  )
}

export default SectionConnect

CSS 代码

.connect-btn {
  display: flex;
  justify-content: space-around;
  padding: 8px 8px 6px 10px;
  background: #FAFAFC;
  border-radius: 78px;
  width: 58%;
  height: 50px;
}

.disable-btn {
  font-family: Sofia Pro;
  font-style: normal;
  font-weight: 600;
  font-size: 16px;
  line-height: 140%;
  color: #435473;
  padding: 4px 8px 0px 16px;
  border-radius: 74px;
  text-decoration: none;
}

.active-btn {
  padding: 8px 8px 0px 16px;
  background: #5582A7;
  border-radius: 74px;
  font-family: Sofia Pro;
  font-style: normal;
  font-weight: 600;
  font-size: 16px;
  line-height: 140%;
  color: #FFFFFF;
  text-decoration: none;
}

【问题讨论】:

  • 尽管您确实应该使用功能状态更新来切换布尔值,但您的代码似乎可以按预期运行。 codesandbox.io/s/toggle-switch-in-reactjs-5gdcy 也许我误解了你想要的预期行为。您想通过单击来选择/切换活动链接吗?

标签: css reactjs react-router


【解决方案1】:

您可以使用NavLinkactiveClassName 来实现您所追求的目标,而无需使用本地组件状态。

import React from "react";
import { BrowserRouter as Router, NavLink } from "react-router-dom";
import './SectionConnect.css';

const SectionConnect = () => {
  return (
    <div className="connect-container">
      <div className="connect-wrapper">
        <h2>How it works</h2>
        <p>
          We connect you with the very best practitioners and most effective
          methods to achieve optimal health.
        </p>
        <div className="connect-btn">
          <NavLink
            to="/"
            exact
            activeClassName="active-btn"
            className="disable-btn"
          >
            For companies
          </NavLink>
          <NavLink
            to="/forIndividuals"
            exact
            activeClassName="active-btn"
            className="disable-btn"
          >
            For individuals
          </NavLink>
        </div>
      </div>
    </div>
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多