1 Hook
以 use 开头的函数被称为 Hook
;
useState
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}
2 状态提升
父组件
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
子组件
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}
MyApp 组件包含了 count
state 以及 handleClick
事件处理函数,并将它们作为 prop 传递给了每个按钮。
MyButton
以读取从父组件传递来的 prop;
点击按钮,state 变量 count
会递增;新的 count
会被作为 prop 传递给每个按钮,因此它们每次展示的都是最新的值;这被称为 “状态提升” 。通过向上移动 state,实现在组件间共享。
3 将React添加到已有项目中
import { createRoot } from 'react-dom/client';
function NavigationBar() {
// TODO: 实际实现一个导航栏
return <h1>Hello from React!</h1>;
}
const domNode = document.getElementById('navigation');
const root = createRoot(domNode);
root.render(<NavigationBar />);
<!DOCTYPE html>
<html>
<head><title>My app</title></head>
<body>
<p>This paragraph is a part of HTML.</p>
<nav id="navigation"></nav>
<p>This paragraph is also a part of HTML.</p>
</body>
</html>