Hook之useState
这个例子用来显示一个计数器。当你点击按钮,计数器的值就会增加:
import React, { useState } from 'react';
function Example() {
// 声明一个叫 “count” 的 state 变量。
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
其中的关键就是const [count, setCount] = useState(0);
[] 中的 唯一参数 就是 count 可称之为 state ,而通过上述例子你可以发现 setCount 则是控制 count 的 函数
useState后面的 () 中则是 count 的初始值,可以是 number ,string ,boolend等类型