Home > Web Front-end > JS Tutorial > body text

React Basics~useState/ count number~

Mary-Kate Olsen
Release: 2024-10-06 20:39:29
Original
704 people have browsed it
  • 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;


Copy after login

・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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template