为什么 onClick 操作不向现有整数添加值

Why doesn't the onClick action add a value to an existing integer

我正在使用 ReactJS + Vite 和 Tailwind CSS 并且我正在尝试将 150 添加到按钮(位于导航栏中)中的 int “tokens”,但我无法让它工作.任何人都可以帮助我吗? 它非常简单(使用 navbar.jsx 和 main.jsx

中的组件

Navbar.jsx(载入main.jsx)

import { Link } from "react-router-dom";
import React, { useState } from 'react';

var tokens = 100;
export default function Navbar() {
  return (
    <div>
      <nav class="bg-slate-800 text-gray-200 h-14 flex items-center rounded-cool flex-row mb-1.5 ">
        {/* tokens */}
          <div class="basis-1/3 flex flex-row justify-end">
            <div class="bg-slate-700 hover:bg-gray-700 transition-all divide-x py-1.5 px-2 mr-2 ml-1 box-content rounded-cool flex flex-row">
              <button class="pr-1.5 hover:text-orange-500
              transition-all" onClick={()=>tokens+=100}>Add Tokens</button>              
               <p
               class="px-1.5 hover:text-orange-500 
               transition-all"
               >
                 {tokens} Tokens
              </p>
            </div>
          </div>

      </nav>
    </div>
  );
}

main.jsx(或

//import of libraries
import { render } from "react-dom";
import { BrowserRouter, Routes, Route,} from "react-router-dom";

//css (TailWind)
import './index.css'

//imports of pages
import App from "./App";
import Cases from "./routes/cases";
import Upgrader from "./routes/upgrader";
import Contracts from "./routes/contracts";
import Inventory from "./routes/inventory";
import Navbar from "./navbar"

//site content
const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
  <Navbar/>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="cases" element={<Cases />} />
      <Route path="upgrader" element={<Upgrader />} />
      <Route path="contracts" element={<Contracts />} />
      <Route path="inventory" element={<Inventory />} />
    </Routes>
  </BrowserRouter>,
  rootElement
);

为了正确使用“useState”,您需要使用以下语法:

export default function Navbar() {   

  const [tokens , setTokens] = useState(100)

    return (

确保将钩子放在功能组件中。

然后更新您的 onClick 以使用您的挂钩:

onClick={()=>setTokens(tokens+100)}