动态 Context
// counter-context.js
export const CounterContext = Taro.createContext(0);
// index.js
class Index extends Component {
render () {
const [ count, setCount ] = useState(0)
return (
<CounterContext.Provider value={count}>
<View className='container'>
<Test />
<Button onClick={() => setCount(0)}>Reset</Button>
<Button onClick={() => setCount(prevCount => prevCount + 1)}>+</Button>
<Button onClick={() => setCount(prevCount => prevCount - 1)}>-</Button>
</View>
</CounterContext.Provider>
)
}
}
// child.js
class Child extends Taro.Component {
shouldComponentUpdate () {
// 即便返回 false 也不会阻止 CounterContext 更新消费它的组件
return false
}
render () {
return <Counter />
}
}
// counter.js
import { CounterContext } from './counter-context.js'
class Counter extends Taro.Component {
static contextType = CounterContext
render () {
const value = this.context
return (
<View>
Count: {value}
</View>
)
}
}
我们在这个例子中把计数器 count
的值通过 CounterContext.Provider
往下传递,Child
组件中虽然禁止了更新,但 Counter
组件在 CounterContext.Provider
的 value
每次变化之后,还是能够订阅更新,收到每次 count
的值