Home  >  Article  >  Web Front-end  >  React Basics~useState/ count number~

React Basics~useState/ count number~

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-06 20:39:29663browse
  • The useState is a react hook that holds a state of the component.
    In this case, the state is a counter.

  • The button increases the state of the counter. The - button decreases the counter.

・src/Example.js


import { useState } from "react";

const Example = () => {
  const [count, setCount] = useState(0);
  return (
    <>
      <CountResult title="count" count={count} />
      <CountUpdate setCount={setCount} />
    </>
  );
};
const CountResult = ({ title, count }) => (
  <h3>
    {title} : {count}
  </h3>
);

const CountUpdate = ({ setCount }) => {
  const countUp = () => {
    setCount((prev) => prev + 1);
  };
  const countDown = () => {
    setCount((prev) => prev - 1);
  };
  return (
    <>
      <button onClick={countUp}>+</button>
      <button onClick={countDown}>-</button>
    </>
  );
};

export default Example;


・Here is the action of countup.

React Basics~useState/ count number~

・Here is the action of countdown.

React Basics~useState/ count number~

The above is the detailed content of React Basics~useState/ count number~. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn