我在使用 useContext 时做错了什么?

what am I doing wrong with useContext?

我正在尝试使用 preact 中的 useContext。看来我做错了什么,因为我的上下文给出了未定义的值。

这是主要文件:

const {render, h, createContext} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import SampleComp from './sample-comp.js'

export const ContextOne = createContext()
export const ContextTwo = createContext()

const RootComp = (props) => {
  return html`
  <ContextOne.Provider value=${'ContextOne'}>
    <ContextTwo.Provider value=${'ContextTwo'}>
      <${SampleComp}/>
    </ContextTwo.Provider>
  </ContextOne.Provider>
  `
}

render(html`<${RootComp} />`, document.body);

这是示例组件:

const {useContext} = window.preactHooks
const {h} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import {ContextOne, ContextTwo} from './index.js'


export default function SampleComp (props) {
  const one = useContext(ContextOne)
  const two = useContext(ContextTwo)
  return html`<div>${one} - ${two}</div>`
}

我在这里做错了什么?几个小时以来我一直在努力弄明白,但一无所知。

我知道了。

刚刚发布问题后,我意识到通过使用 htm,我需要将模板字符串中的提供程序包装为一个变量。所以正确的是:

const RootComp = (props) => {
  return html`
  <${ContextOne.Provider} value=${'ContextOne'}>
    <${ContextTwo.Provider} value=${'ContextTwo'}>
      <${SampleComp}/>
    </ContextTwo.Provider>
  </ContextOne.Provider>
  `
}