响应式
声明状态
React
import { useState } from "react";
export default function Name() {
const [name] = useState("张三");
return <h1>你好 {name}</h1>;
}
Qwik
import { component$, useSignal } from "@builder.io/qwik";
export const Name = component$(() => {
const name = useSignal("张三");
return <h1>你好 {name.value}</h1>;
});
更新状态
React
import { useEffect, useState } from "react";
export default function Name() {
const [name, setName] = useState("张三");
useEffect(() => {
setName("李四");
}, []);
return <h1>你好 {name}</h1>;
}
Qwik
import { component$, useTask$, useSignal } from "@builder.io/qwik";
export const Name = component$(() => {
const name = useSignal("张三");
useTask$(() => {
name.value = "李四";
});
return <h1>你好 {name.value}</h1>;
});
计算属性
React
import { useState } from "react";
export default function DoubleCount() {
const [count] = useState(10);
const doubleCount = count * 2;
return <div>{doubleCount}</div>;
}
Qwik
import { component$, useSignal, useComputed$ } from "@builder.io/qwik";
export const DoubleCount = component$(() => {
const count = useSignal(10);
const doubleCount = useComputed$(() => count.value * 2);
return <div>{doubleCount.value}</div>;
});
模板语法
最简模板
React
export default function HelloWorld() {
return <h1>你好,世界</h1>;
}
Qwik
export const HelloWorld = () => {
return <div>你好,世界</div>;
};
样式
React
import "./style.css";
export default function CssStyle() {
return (
<>
<h1 className="title">我是红色的</h1>
<button style={{ fontSize: "10rem" }}>我是一个按钮</button>
</>
);
}
Qwik
import { component$, useStyles$ } from "@builder.io/qwik";
export const App = component$(() => {
useStyles$(`
.title {
color: red;
}
`);
return (
<>
<h1 class="title">我是红色的</h1>
<button style={{ "font-size": "10rem" }}>我是一个按钮</button>
</>
);
});
DOM循环
React
export default function Colors() {
const colors = ["红", "绿", "蓝"];
return (
<ul>
{colors.map((color) => (
<li key={color}>{color}</li>
))}
</ul>
);
}
Qwik
import { component$ } from "@builder.io/qwik";
export const Colors = component$(() => {
const colors = ["红", "绿", "蓝"];
return (
<ul>
{colors.map((color) => (
<li key={color}>{color}</li>
))}
</ul>
);
});
点击事件
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>
</>
);
}
Qwik
import { component$, useSignal, $ } from "@builder.io/qwik";
export const Counter = component$(() => {
const count = useSignal(0);
const incrementCount = $(() => {
count.value++;
});
return (
<>
<p>计数器: {count.value}</p>
<button onClick$={incrementCount}>Increment</button>
</>
);
});
DOM引用
React
import { useEffect, useRef } from "react";
export default function InputFocused() {
const inputElement = useRef(null);
useEffect(() => inputElement.current.focus(), []);
return <input type="text" ref={inputElement} />;
}
Qwik
import { component$, useVisibleTask$, useSignal } from "@builder.io/qwik";
export const InputFocused = component$(() => {
const inputElement = useSignal<HTMLInputElement>();
useVisibleTask$(({ track }) => {
const el = track(inputElement);
el?.focus();
});
return <input type="text" ref={inputElement} />;
});
条件渲染
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>
</>
);
}
Qwik
import { $, component$, useComputed$, useSignal } from "@builder.io/qwik";
export const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
export const TrafficLight = component$(() => {
const lightIndex = useSignal(0);
const light = useComputed$(() => TRAFFIC_LIGHTS[lightIndex.value]);
const nextLight = $(() => {
lightIndex.value = (lightIndex.value + 1) % TRAFFIC_LIGHTS.length;
});
return (
<>
<button onClick$={nextLight}>下一个灯</button>
<p>现在亮着的是: {light.value}</p>
<p>
你应该 {light.value === "红灯" && <span>停下</span>}
{light.value === "黄灯" && <span>慢行</span>}
{light.value === "绿灯" && <span>赶紧走</span>}
</p>
</>
);
});
生命周期
组件加载时
React
import { useState, useEffect } from "react";
export default function PageTitle() {
const [pageTitle, setPageTitle] = useState("");
useEffect(() => {
setPageTitle(document.title);
}, []);
return <p>页面标题: {pageTitle}</p>;
}
Qwik
import { component$, useVisibleTask$, useStore } from "@builder.io/qwik";
export const App = component$(() => {
const store = useStore({
pageTitle: "",
});
useVisibleTask$(() => {
store.pageTitle = document.title;
});
return <p>页面标题: {store.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>;
}
Qwik
import { component$, useVisibleTask$, useStore } from "@builder.io/qwik";
export const App = component$(() => {
const store = useStore({
time: new Date().toLocaleTimeString(),
});
useVisibleTask$(({ cleanup }) => {
const timer = setInterval(() => {
store.time = new Date().toLocaleTimeString();
}, 1000);
cleanup(() => clearInterval(timer));
});
return <p>当前时间: {store.time}</p>;
});
组件组合
组件Props传参
React
import UserProfile from "./UserProfile.jsx";
export default function App() {
return (
<UserProfile
name="张三"
age={20}
favouriteColors={["green", "blue", "red"]}
isAvailable
/>
);
}
Qwik
import { component$ } from "@builder.io/qwik";
import UserProfile from "./UserProfile";
const App = component$(() => {
return (
<UserProfile
name="张三"
age={20}
favouriteColors={["green", "blue", "red"]}
isAvailable
/>
);
});
export default App;
向父组件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>
</>
);
}
Qwik
import { $, component$, useStore } from "@builder.io/qwik";
import AnswerButton from "./AnswerButton";
const App = component$(() => {
const store = useStore({
isHappy: true,
});
const onAnswerNo = $(() => {
store.isHappy = false;
});
const onAnswerYes = $(() => {
store.isHappy = true;
});
return (
<>
<p>你快乐吗?</p>
<AnswerButton onYes$={onAnswerYes} onNo$={onAnswerNo} />
<p style={{ fontSize: 50 }}>{store.isHappy ? "😀" : "😥"}</p>
</>
);
});
export default App;
slot插槽
React
import FunnyButton from "./FunnyButton.jsx";
export default function App() {
return <FunnyButton>点我!</FunnyButton>;
}
Qwik
import FunnyButton from "./FunnyButton";
export default function App() {
return <FunnyButton>点我!</FunnyButton>;
}
slot插槽内容
React
import FunnyButton from "./FunnyButton.jsx";
export default function App() {
return (
<>
<FunnyButton />
<FunnyButton>这是传到slot的内容!</FunnyButton>
</>
);
}
Qwik
import FunnyButton from "./FunnyButton";
export default function App() {
return (
<>
<FunnyButton />
<FunnyButton>这是传到slot的内容!</FunnyButton>
</>
);
}
上下文
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>
</>
);
}
Qwik
import {
component$,
useStore,
useContextProvider,
createContext,
$,
} from "@builder.io/qwik";
import UserProfile from "./UserProfile";
export const UserContext = createContext("user-context");
const App = component$(() => {
const user = useStore({
id: 1,
username: "abcdefg",
email: "[email protected]",
});
const updateUsername = $((newUsername) => {
user.username = newUsername;
});
useContextProvider(UserContext, { user, updateUsername });
return (
<>
<h1>欢迎回来, {user.username}</h1>
<UserProfile />
</>
);
});
export default App;
表单输入
输入框
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} />
</>
);
}
Qwik
import { component$, useSignal } from "@builder.io/qwik";
const InputHello = component$(() => {
const text = useSignal("");
return (
<>
<p>{text.value}</p>
<input bind:value={text} />
</>
);
});
export default InputHello;
复选框
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>
</>
);
}
Qwik
import { component$, useSignal } from "@builder.io/qwik";
const IsAvailable = component$(() => {
const isAvailable = useSignal(false);
return (
<>
<input id="is-available" type="checkbox" bind:checked={isAvailable} />
<label for="is-available">这是一个checkbox</label>
</>
);
});
export default IsAvailable;
单选框
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>
</>
);
}
Qwik
import { component$, useSignal } from "@builder.io/qwik";
const PickPill = component$(() => {
const pickedColor = useSignal("red");
return (
<>
<div>你选择了: {pickedColor.value}</div>
<input
id="blue-pill"
type="radio"
bind:value={pickedColor}
checked={pickedColor.value === "blue"}
value="blue"
/>
<label for="blue-pill">蓝色</label>
<input
id="red-pill"
type="radio"
checked={pickedColor.value === "red"}
bind:value={pickedColor}
value="red"
/>
<label for="red-pill">红色</label>
</>
);
});
export default PickPill;
选择器
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>
);
}
Qwik
import { component$, useSignal } from "@builder.io/qwik";
export const colors = [
{ id: 1, text: "红" },
{ id: 2, text: "蓝" },
{ id: 3, text: "绿" },
{ id: 4, text: "灰", isDisabled: true },
];
const ColorSelect = component$(() => {
const selectedColorId = useSignal("2");
return (
<select bind:value={selectedColorId}>
{colors.map((color) => (
<option
key={color.id}
value={color.id}
disabled={color.isDisabled}
selected={`${color.id}` === selectedColorId.value}
>
{color.text}
</option>
))}
</select>
);
});
export default ColorSelect;
Web应用特性
渲染应用
React
<!doctype html>
<html>
<body>
<div id="app"></div>
<script type="module" src="./main.jsx"></script>
</body>
</html>
Qwik
<!doctype html>
<html>
<body>
<div id="app"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
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>
)
)}
</>
);
}
Qwik
import { component$, useResource$, Resource } from "@builder.io/qwik";
type UsersResponse = {
results: {
picture: {
thumbnail: string;
};
name: {
first: string;
last: string;
};
}[];
};
export async function fetchUsers() {
return (await fetch("https://randomuser.me/api/?results=3")).json();
}
export const App = component$(() => {
const data = useResource$<UsersResponse>(fetchUsers);
return (
<Resource
value={data}
onPending={() => <p>正在获取用户信息……</p>}
onRejected={() => <p>获取用户信息出错</p>}
onResolved={({ results: users }) => (
<ul>
{users.map((user) => (
<li>
<img src={user.picture.thumbnail} alt="user" />
<p>
{user.name.first} {user.name.last}
</p>
</li>
))}
</ul>
)}
/>
);
});