【问题标题】:what am I doing wrong with useContext?我在 useContext 做错了什么?
【发布时间】:2021-01-02 15:34:58
【问题描述】:

我正在尝试使用来自preactuseContext。看来我做错了什么,因为我的 Context 给出了未定义的值。

这里是主文件:

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

我在这里做错了什么?我已经尝试了几个小时,但不知道。

【问题讨论】:

    标签: javascript preact use-context


    【解决方案1】:

    我明白了。

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

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

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 2021-04-19
      • 2017-03-13
      • 2017-01-18
      相关资源
      最近更新 更多