使用 Hooks 的计数器

2025年11月29日 作者:管理员

示例代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>React Hooks 计数器</title>
  <script crossorigin src="https://unpkg.com/react@18.3.1/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; padding: 20px; }
    button { margin: 5px; padding: 8px 16px; font-size: 16px; }
  </style>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function Counter() {
      const [count, setCount] = React.useState(0);

      return (
        <div>
          <p>当前计数: {count}</p>
          <button onClick={() => setCount(count + 1)}>
            增加
          </button>
          <button onClick={() => setCount(count - 1)}>
            减少
          </button>
        </div>
      );
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Counter />);
  </script>
</body>
</html>