hook 是个函数。
使用 react hook 可以利用 react 的功能:例如 state 或 lifecycle 方法。
react 有若干内建的 hook 函数,用户也可以自定义 hook 函数。
react 组件有两种:基于类的组件,以及无状态 stateless 函数组件。但是使用 hook,函数就有可能是有状态的。
hook 函数 useState
以下的例子,用3个button : + - reset 改变数字,并使用 input 修改文字值,使用两次 useState,分别跟踪 count 和 text:
index.js:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import reportWebVitals from "./reportWebVitals";
const App = (props) => {
// count, setCount 理论上可以任意命名
// 不同于类组件,函数组件中的state不需要是一个对象
const [count, setCount] = useState(props.count);
const [text, setText] = useState("");
return (
<div>
<p> The current {text || "count"} is {count} </p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(count - 1)}>-1</button>
<button onClick={() => setCount(props.count)}>reset</button>
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
);
};
// 组件默认props
App.defaultProps = {
count: 0,
};
ReactDOM.render(
<React.StrictMode>
<App count={3} />
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
useState
返回值是一个带有两个元素是数组,第1个元素是当前状态值,第2个是用来更新 state 的函数。