面试题答案
一键面试- 创建上下文:
使用
createContext
函数创建一个上下文对象。这个上下文对象包含Provider
和Context
两个属性。Provider
用于向后代组件提供数据,Context
用于后代组件消费数据。import { createContext } from'solid-js'; // 创建上下文 const MyContext = createContext();
- 提供上下文:
在顶层组件中,使用
MyContext.Provider
包裹需要共享状态的子组件树,并通过value
属性传递状态数据。import { createSignal } from'solid-js'; import { MyContext } from './MyContext'; const ParentComponent = () => { const [sharedState, setSharedState] = createSignal('初始状态'); return ( <MyContext.Provider value={[sharedState, setSharedState]}> {/* 子组件树 */} </MyContext.Provider> ); };
- 消费上下文:
在深层子组件中,使用
useContext
函数来获取顶层组件传递的状态数据。import { useContext } from'solid-js'; import { MyContext } from './MyContext'; const DeepChildComponent = () => { const [sharedState, setSharedState] = useContext(MyContext); return ( <div> <p>共享状态: {sharedState()}</p> <button onClick={() => setSharedState('新状态')}>更新状态</button> </div> ); };
完整示例:
import { createContext, createSignal, useContext } from'solid-js';
// 创建上下文
const MyContext = createContext();
const ParentComponent = () => {
const [sharedState, setSharedState] = createSignal('初始状态');
return (
<MyContext.Provider value={[sharedState, setSharedState]}>
<DeepChildComponent />
</MyContext.Provider>
);
};
const DeepChildComponent = () => {
const [sharedState, setSharedState] = useContext(MyContext);
return (
<div>
<p>共享状态: {sharedState()}</p>
<button onClick={() => setSharedState('新状态')}>更新状态</button>
</div>
);
};
export default ParentComponent;