0%
提供者与消费者模式
用于组孙组件通讯的场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import { useState, createContext, useContext } from 'react'
const context = createContext() const
function parent() { return( <context.Provider value={{ color, setColor, }} > ... </context.Provider> ) }
function Child() { return( <context.Consumer> {/*以函数传参形式消费*/} { value => ... } </context.Consumer> ) }
function Child() { const value = useContext(context) return() { {value.xxx}... } }
|