【问题标题】:Need to click twice to update the state in react hooks. toggle button需要点击两次才能更新 react hooks 中的状态。切换按钮
【发布时间】:2020-10-28 10:20:37
【问题描述】:

我需要在按钮上单击两次才能更新状态。 我有两个按钮。当我在按钮之间切换时,文本应该会改变。

我发现了一些与此相关的问题,但对我没有用。

请找到下面的代码。

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

const SectionConnect = () => {

const [activeButton, setActiveButton] = useState("company");

function toggleButton() {
  setActiveButton(activeButton==="company" ? "individual" : "company");

}



  return (
    <div className="connect-container">
      <div className="connect-wrapper">
        <h2>How it works</h2>
        
    {activeButton==="company"?<p>
          We help your employees maximise potential through a bespoke, science-backed wellbeing platform. 
        </p>:<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"
           onClick={toggleButton}
          >
            For companies
          </NavLink>
          <NavLink
            to="/forIndividuals"
            exact
            activeClassName="active-btn"
            className="disable-btn"
            onClick={toggleButton}
          >
            For individuals
          </NavLink>
          
        </div>
      </div>
    </div>
  );
};

export default SectionConnect

无法理解我哪里出错了。 提前致谢!

【问题讨论】:

  • 能不能把代码加到网上的代码sn-p中让我查看结果?
  • 你为什么使用 navlink ?它用于导航,所以可能首先点击它的导航

标签: reactjs react-router react-hooks


【解决方案1】:

在这样的切换按钮调用onClick={()=&gt; toggleButton()}

【讨论】:

  • 是的,首先点击它的导航为什么你使用navlink?
  • 使用 Navlink 转到其他页面,我可以同时使用 Navlink 吗,1. onClick 并转到其他页面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
相关资源
最近更新 更多