面试题答案
一键面试- 安装依赖:
在Qwik项目中,确保已经安装了Qwik相关依赖。如果是新创建的项目,可以使用
npm create qwik@latest
来初始化项目。 - 创建上下文:
使用
createContext
函数来创建上下文对象。在Qwik中,createContext
来自@builder.io/qwik
库。 示例代码如下:import { createContext } from '@builder.io/qwik'; // 创建用户登录状态上下文 const UserLoginContext = createContext<{ isLoggedIn: boolean } | null>(null);
- 提供上下文:
在需要传递用户登录状态信息的组件树的上层组件中,使用
useContextProvider
来提供上下文。import { component$, useContextProvider } from '@builder.io/qwik'; const App = component$(() => { const userLoginState = { isLoggedIn: true }; useContextProvider(UserLoginContext, userLoginState); return ( <div> {/* 组件树内容 */} </div> ); });
- 消费上下文:
在需要获取用户登录状态信息的子组件中,使用
useContext
来消费上下文。import { component$, useContext } from '@builder.io/qwik'; const ChildComponent = component$(() => { const userLoginState = useContext(UserLoginContext); return ( <div> {userLoginState?.isLoggedIn ? '用户已登录' : '用户未登录'} </div> ); });