React:如何在单击后禁用按钮

下面的这个例子展示了如何在 React 中单击某个按钮后禁用它。这在您希望防止用户重复点击多次的情况下很有用,例如提交表单、以促销价格购买产品(每人只能购买一个)等。

示例预览

React:如何在单击后禁用按钮

完整代码  带解释):

// KindaCode.com
// src/App.js
import { useState } from 'react';

function App() {
  // this determines whether the button is disabled or not
  const [isDisabled, setIsDisabled] = useState(false);

  // This function is called when the button is clicked the first time
  const handleClick = () => {
    alert('Hi there!');
    setIsDisabled(true);
  };

  return (
    <div style={styles.container}>
      <button
        disabled={isDisabled}
        onClick={handleClick}
        // this is the style for the button
        style={isDisabled ? styles.buttonDisabled : styles.button}
      >
        Button
      </button>
    </div>
  );
}

// Styles
const styles = {
  container: {
    width: '100vw',
    height: '100vh',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    padding: '10px 30px',
    cursor: 'pointer',
  },
  buttonDisabled: {
    padding: '10px 30px',
    cursor: 'not-allowed',
  },
};

export default App;