import React from 'react'

interface AppContextInterface {
    name: string
    author: string
    url: string
}
const sampleAppContext: AppContextInterface = {
    name: "Using React Context in a Typescript App",
    author: "zyg",
    url: "http://www.example.com",
}

// 创建context 上下文
const AppCtx = React.createContext<AppContextInterface>(sampleAppContext)

export const Demo: React.FC = () => {
    return (
        <div>
            <AppCtx.Provider value={sampleAppContext}>
                <div>hello</div>
                {/* 子组件 */}
                <PostInfo />
            </AppCtx.Provider>
        </div>
    )
}

export const PostInfo = () => {
    // 使用context上下文
    const { name, author, url } = React.useContext(AppCtx)

    return (
        <div>
            Name: { name}, Author: { author}, Url:{" "}
            { url}
        </div>
    )
}

相关文章:

  • 2022-12-23
  • 2021-05-19
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-29
  • 2022-02-25
  • 1970-01-01
  • 2022-12-23
  • 2021-09-20
相关资源
相似解决方案