react中useContext实现父子组件传值

Example4.jsx

    import React, { useState,createContext,useContext} from 'react'

const CountContext = createContext();

function Counter(){
    let count = useContext(CountContext)

    return (
        <h2>{count}</h2>
    )
}

function Example4(){

    const [count, setCount] = useState(0); //数组第一个是0 第二是一个函数

    return (
        <div>
            <p>You Clicked {count} times</p>
            <button onClick={() => {setCount(count+1)}}>Click me</button>

            <CountContext.Provider>
                <Counter/>
            </CountContext.Provider>
        </div>


    )
}

export default Example4

App.JSX

import React, { Component } from 'react'
// import Count from "./components/Count/index"
// import HooksDemo from "./components/Hooks/index"
import Example4 from "./components/Hooks/Example4"

export default class App extends Component {
	render() {
		return (
			<div>
			{/* <Count></Count> */}
			{/* <HooksDemo></HooksDemo> */}

			<Example4></Example4>

			</div>
			)
	}
}

运行结果

原文地址:https://www.cnblogs.com/malong1992/p/15317850.html