我在 useContext 上做错了什么?

问题描述

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

这里是主文件

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>
  `
}