useState 是 React 提供的一个 Hook,用于在函数组件中添加状态。

使用 useState 需要先导入它:

import React, { useState } from 'react';

然后,在函数组件中使用它:

function MyComponent() { 
  // 使用 useState 定义一个状态变量和一个更新该变量的函数 
  const [count, setCount] = useState(0); 

  // 在组件中可以使用 count 变量和 setCount 函数 
  return ( 
    <div> 
      <p>Count: {count}</p> 
      <button onClick={() => setCount(count + 1)}>Increment</button> 
      <button onClick={() => setCount(count - 1)}>Decrement</button> 
    </div> 
  ); 
} 

在上面的例子中,useState 接受初始状态值(0),并返回一个包含了当前状态值(count)和更新该状态值的函数(setCount)的数组。然后,我们可以在组件中使用 count 变量来展示当前状态值,使用 setCount 函数来更新状态。在点击增加和减少按钮时,调用 setCount 函数并传入新的状态值,React 会重新渲染组件,并显示更新后的状态值。

React useState Hook 使用教程 - 状态管理利器

原文地址: https://www.cveoy.top/t/topic/qfDV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录