React 组件中的通信分为三种,必须依赖React.createContext()
const myContext = React.createContext()
1、通过标签<Consumer>
2、通过useContext(myContext)
3、通过static contextType = myContext
import React, { Component, useContext } from 'react'
import { Button } from 'antd'
const myContext = React.createContext()
const { Provider, Consumer } = myContext
const sayHai = (name) => {
console.log(`${name} say hai!`)
}
// function App(props) {
// console.log('App:', props)
// return (
// <button onClick={() => props.say(props.name)}>{props.name}</button>
// )
// }
// function App2(props) {
// const ctx = useContext(myContext)
// return (
// <button onClick={() => ctx.say(`${ctx.name} App2`)}>{ctx.name}</button>
// )
// }
// class App3 extends Component {
// static contextType = myContext
// render() {
// return (
// <button onClick={() => this.context.say(`${this.context.name} App3`)}>{this.context.name}</button>
// )
// }
// }
// class ContextTest extends Component {
// render() {
// return (
// <Provider value={{ name: '张三', say: sayHai }}>
// <Consumer>
// { (value) => <App {...value}></App>}
// </Consumer>
// <App2></App2>
// <App3></App3>
// </Provider>
// )
// }
// }
// export default ContextTest
function App(Com) {
return (props) => (
// 必须写value
<Provider value={{name: '老五', say: sayHai}}>
<Com {...props}/>
</Provider>
)
}
class ContextTest extends Component {
render() {
return (
<Consumer>
{/* consumer必须是函数 */}
{value => <button onClick={() => value.say(value.name)}>{value.name}</button>}
</Consumer>
)
}
}
export default App(ContextTest)