响应式
声明状态
更新状态
模板语法
样式
React
import "./style.css";
export default function CssStyle() {
return (
<>
<h1 className="title">我是红色的</h1>
<button style={{ fontSize: "10rem" }}>我是一个按钮</button>
</>
);
}
DOM循环
点击事件
React
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
function incrementCount() {
setCount((count) => count + 1);
}
return (
<>
<p>计数器: {count}</p>
<button onClick={incrementCount}>+1</button>
</>
);
}
DOM引用
条件渲染
React
import { useState } from "react";
const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
export default function TrafficLight() {
const [lightIndex, setLightIndex] = useState(0);
const light = TRAFFIC_LIGHTS[lightIndex];
function nextLight() {
setLightIndex((lightIndex + 1) % TRAFFIC_LIGHTS.length);
}
return (
<>
<button onClick={nextLight}>下一个灯</button>
<p>现在亮着的是: {light}</p>
<p>
你应该
{light === "红灯" && <span>停下</span>}
{light === "黄灯" && <span>慢行</span>}
{light === "绿灯" && <span>赶紧走</span>}
</p>
</>
);
}
static const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
<let/lightIndex=0>
<const/light=TRAFFIC_LIGHTS[lightIndex]>
<button onClick() { lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length }>
下一个灯
</button>
<p>现在亮着的是: ${light}</p>
<p>
你应该
<if=light === "红灯">停下</if>
<else if=light === "黄灯">慢行</else>
<else>赶紧走</else>
</p>
生命周期
组件加载时
React
import { useState, useEffect } from "react";
export default function PageTitle() {
const [pageTitle, setPageTitle] = useState("");
useEffect(() => {
setPageTitle(document.title);
}, []);
return <p>页面标题: {pageTitle}</p>;
}
组件卸载时
React
import { useState, useEffect } from "react";
export default function Time() {
const [time, setTime] = useState(new Date().toLocaleTimeString());
useEffect(() => {
const timer = setInterval(() => {
setTime(new Date().toLocaleTimeString());
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>当前时间: {time}</p>;
}
组件组合
组件Props传参
向父组件emit事件
React
import { useState } from "react";
import AnswerButton from "./AnswerButton.jsx";
export default function App() {
const [isHappy, setIsHappy] = useState(true);
function onAnswerNo() {
setIsHappy(false);
}
function onAnswerYes() {
setIsHappy(true);
}
return (
<>
<p>你快乐吗?</p>
<AnswerButton onYes={onAnswerYes} onNo={onAnswerNo} />
<p style={{ fontSize: 50 }}>{isHappy ? "😀" : "😥"}</p>
</>
);
}
slot插槽
slot插槽内容
上下文
React
import { useState } from "react";
import UserProfile from "./UserProfile";
import { UserContext } from "./UserContext";
export default function App() {
const [user, setUser] = useState({
id: 1,
username: "abcdefg",
email: "[email protected]",
});
function updateUsername(newUsername) {
setUser((userData) => ({ ...userData, username: newUsername }));
}
return (
<>
<h1>欢迎回来, {user.username}</h1>
<UserContext.Provider value={{ ...user, updateUsername }}>
<UserProfile />
</UserContext.Provider>
</>
);
}
<let/user={
id: 1,
username: "abcdefg",
email: "[email protected]",
}>
<const/updateUsername(newUsername) {
user = { ...user, username: newUsername };
}>
<h1>欢迎回来, ${user.username}</h1>
<context={ ...user, updateUsername }>
<UserProfile />
</context>
表单输入
输入框
React
import { useState } from "react";
export default function InputHello() {
const [text, setText] = useState("你好世界");
function handleChange(event) {
setText(event.target.value);
}
return (
<>
<p>{text}</p>
<input value={text} onChange={handleChange} />
</>
);
}
复选框
React
import { useState } from "react";
export default function IsAvailable() {
const [isAvailable, setIsAvailable] = useState(false);
function handleChange() {
setIsAvailable(!isAvailable);
}
return (
<>
<input
id="is-available"
type="checkbox"
checked={isAvailable}
onChange={handleChange}
/>
<label htmlFor="is-available">这是一个checkbox</label>
</>
);
}
单选框
React
import { useState } from "react";
export default function PickPill() {
const [picked, setPicked] = useState("red");
function handleChange(event) {
setPicked(event.target.value);
}
return (
<>
<div>你选择了: {picked}</div>
<input
id="blue-pill"
checked={picked === "blue"}
type="radio"
value="blue"
onChange={handleChange}
/>
<label htmlFor="blue-pill">蓝色</label>
<input
id="red-pill"
checked={picked === "red"}
type="radio"
value="red"
onChange={handleChange}
/>
<label htmlFor="red-pill">红色</label>
</>
);
}
选择器
React
import { useState } from "react";
const colors = [
{ id: 1, text: "红" },
{ id: 2, text: "蓝" },
{ id: 3, text: "绿" },
{ id: 4, text: "灰", isDisabled: true },
];
export default function ColorSelect() {
const [selectedColorId, setSelectedColorId] = useState(2);
function handleChange(event) {
setSelectedColorId(event.target.value);
}
return (
<select value={selectedColorId} onChange={handleChange}>
{colors.map((color) => (
<option key={color.id} value={color.id} disabled={color.isDisabled}>
{color.text}
</option>
))}
</select>
);
}
static const colors = [
{ id: 1, text: "红" },
{ id: 2, text: "蓝" },
{ id: 3, text: "绿" },
{ id: 4, text: "灰", isDisabled: true },
];
<let/selectedColorId=2>
<select value:=selectedColorId>
<for|{ id, isDisabled, text }| of=colors>
<option value=id disabled=isDisabled>
${text}
</option>
</for>
</select>
Web应用特性
渲染应用
fetch获取数据
React
import useFetchUsers from "./useFetchUsers";
export default function App() {
const { isLoading, error, data: users } = useFetchUsers();
return (
<>
{isLoading ? (
<p>正在获取用户信息……</p>
) : error ? (
<p>获取用户信息出错</p>
) : (
users && (
<ul>
{users.map((user) => (
<li key={user.login.uuid}>
<img src={user.picture.thumbnail} alt="user" />
<p>
{user.name.first} {user.name.last}
</p>
</li>
))}
</ul>
)
)}
</>
);
}
<try>
<await|{ results: users }|=fetch("https://randomuser.me/api/?results=3").then(res => res.json())>
<ul>
<for|{ picture, name }| of=users>
<li>
<img src=picture.thumbnail alt="user">
<p>${name.first} ${name.last}</p>
</li>
</for>
</ul>
</await>
<@placeholder>
<p>正在获取用户信息……</p>
</@placeholder>
<@catch|error|>
<p>获取用户信息出错</p>
</@catch>
</try>