动态 Context

  1. // counter-context.js
  2. export const CounterContext = Taro.createContext(0);
  3. // index.js
  4. class Index extends Component {
  5. render () {
  6. const [ count, setCount ] = useState(0)
  7. return (
  8. <CounterContext.Provider value={count}>
  9. <View className='container'>
  10. <Test />
  11. <Button onClick={() => setCount(0)}>Reset</Button>
  12. <Button onClick={() => setCount(prevCount => prevCount + 1)}>+</Button>
  13. <Button onClick={() => setCount(prevCount => prevCount - 1)}>-</Button>
  14. </View>
  15. </CounterContext.Provider>
  16. )
  17. }
  18. }
  19. // child.js
  20. class Child extends Taro.Component {
  21. shouldComponentUpdate () {
  22. // 即便返回 false 也不会阻止 CounterContext 更新消费它的组件
  23. return false
  24. }
  25. render () {
  26. return <Counter />
  27. }
  28. }
  29. // counter.js
  30. import { CounterContext } from './counter-context.js'
  31. class Counter extends Taro.Component {
  32. static contextType = CounterContext
  33. render () {
  34. const value = this.context
  35. return (
  36. <View>
  37. Count: {value}
  38. </View>
  39. )
  40. }
  41. }


我们在这个例子中把计数器 count 的值通过 CounterContext.Provider 往下传递,Child 组件中虽然禁止了更新,但 Counter 组件在 CounterContext.Providervalue 每次变化之后,还是能够订阅更新,收到每次 count 的值

消费多个 Context

image.png