面试题答案
一键面试方法及关键概念
- 使用
$
符号标记响应式变量:在Qwik中,通过在变量前加上$
符号将其定义为响应式变量。这样,当这个变量的值发生变化时,依赖它的组件会自动重新渲染。 - Context API:Qwik提供了类似于React的Context API来实现跨组件状态共享。可以创建一个上下文对象,将响应式状态放入其中,然后通过
useContext
等方法在不同组件间共享状态。
示例代码
- 创建共享状态文件
shared.ts
import { component$, useContext, createContext } from '@builder.io/qwik';
// 创建上下文
const SharedContext = createContext();
// 定义共享的响应式状态
const sharedState = component$(() => {
const count = 0;
const increment = () => {
count.value++;
};
return {
count,
increment
};
});
export { SharedContext, sharedState };
- 父组件
Parent.tsx
import { component$, useContext } from '@builder.io/qwik';
import { SharedContext, sharedState } from './shared';
const Parent = component$(() => {
const state = useContext(SharedContext, sharedState);
return (
<div>
<p>Count: {state.count.value}</p>
<Child />
</div>
);
});
export default Parent;
- 子组件
Child.tsx
import { component$, useContext } from '@builder.io/qwik';
import { SharedContext } from './shared';
const Child = component$(() => {
const state = useContext(SharedContext);
return (
<button onClick={() => state.increment()}>Increment</button>
);
});
export default Child;
在上述代码中,sharedState
定义了共享的响应式状态count
和修改状态的方法increment
。Parent
组件通过useContext
获取共享状态并展示count
的值,Child
组件同样通过useContext
获取状态并提供按钮来调用increment
方法修改共享状态,从而实现不同组件间状态共享。