react 函数组件和类组件混用

如果把类组件C 注释掉 函数组件D 可以正常渲染
但是如果把类组件的C 解开注释 函数组件D 就不能渲染
有兄弟知道为什么吗

img


img


img

源代码:

import React, { Component } from "react"

const UserNameContext = React.createContext()

export default class A extends Component {
    state = { username: "tom" }
    render() {
        return (
            <div>
                <h3>我是A组件</h3>
                <h4>我的用户名是{this.state.username}</h4>
                <UserNameContext.Provider
                    value={{ username: this.state.username, age: 18 }}
                >
                    <B />
                </UserNameContext.Provider>
            </div>
        )
    }
}
class B extends Component {
    render() {
        return (
            <div>
                <div>我是B组件</div>
                <h4>我从A组件接收到的用户名是??</h4>
                <D />
            </div>
        )
    }
}

// class C extends Component {
//     // 声明一下
//     static contextType = UserNameContext
//     render() {
//         console.log(this)
//         return (
//             <div>
//                 <div>我是C 组件</div>
//                 <h4>我从A组件接收到的用户名是{this.context.username}{this.context.age}</h4>
//             </div>
//         )
// }

function D() {
    return (
        <div>
            <div>我是D 组件</div>
            <h4>
                我从A组件接收到的用户名是
                <UserNameContext.Consumer>
                    {
                        value=>{
                            return `${value.username},年龄是${value.age}`
                        }
                    }
                </UserNameContext.Consumer>
            </h4>
        </div>
    )
}

第一 class C 不完整 少 } 结尾括号
第二 D() 方法是 class C 中的 还是全局的,如果是class C 中的 写法不正确,如果是 全局的,把class C 不全完整的 } 括号就可以了
建议用一些代码补全的软件,报错提示位置标准的 软件编写。前端推荐软件 Dreamweaver,VSCode

鼠标放到 function D的红色波浪线上提示什么?