React:单击时更改按钮文本

下面的示例向您展示了如何在 React 中单击按钮后更改其文本。我们将使用useState挂钩来完成工作。

应用预览

React:单击时更改按钮文本

编码

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

function App() {
  // Button Text
  const [buttonText, setButtonText] = useState('Hello World');

  // This function will be called when the button is clicked
  const handleClick = () => {
    setButtonText('Goodbye, World!');
  };

  return (
    <div style={{ padding: 30 }}>
      <button onClick={handleClick} style={{ padding: '10px 30px' }}>
        {/* Button Text */}
        {buttonText}
      </button>
    </div>
  );
}

export default App;

解释

  1. 将按钮文本存储在状态变量中,以便我们可以通过编程方式对其进行更新:
const [buttonText, setButtonText] = useState('Hello World');

2.设置onClick事件的处理函数:

<button onClick={handleClick}>{buttonText}</button>

3.调用状态更新函数设置新的按钮文本:

const handleClick = () => {
    setButtonText('Goodbye, World!');
};