更新界面

来源: 2024-05-26 14:24:28 播报

组件中添加 state。

1、从 React 引入 useState:

import { useState } from 'react';

2、在组件中声明一个 state 变量,useState中的参数是默认值:

function MyButton() {
  const [count, setCount] = useState(0);
  // ...
}

useState方法返回一个数组。

第一个元素是state 状态名称。

第二个元素是更新state 状态的函数。