React中content的基本用法

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>
    )
}
posted @ 2020-11-24 13:35  yaogengzhu  阅读(1369)  评论(0编辑  收藏  举报