简述使用哪个Hook可以为函数组件添加state ?
参考答案:
使用 React.useState()
这个 Hook 可以为函数组件添加 state。useState
是 React 16.8.0 版本引入的一个新特性,允许在函数组件中使用 state 和其他的 React 特性。
useState
的语法如下:
const [stateVariable, setStateFunction] = React.useState(initialValue);
这里,stateVariable
是当前的 state 值,setStateFunction
是一个函数,用于更新这个 state 值。initialValue
是 state 的初始值。
例如,你可以这样使用 useState
:
import React, { useState } from 'react';
function Example() {
// 声明一个新的 state 变量,名为 "count",初始值为 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
在这个例子中,count
是一个 state 变量,setCount
是一个用于更新 count
的函数。每次用户点击按钮时,count
的值就会增加 1。