We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
功能:Context 旨在共享一个组件树内可被视为 “全局” 的数据,例如当前经过身份验证的用户,主题或首选语言等。(ps:树中的许多组件以及不同的嵌套级别可以访问相同的数据。)
//.context.js文件中 import React, { Component } from 'react' const tryContext = React.createContext({ aaa: 28288 }) export { tryContext }
主要是Provider Consumer这对生产者和消费者
import { tryContext } from '../components/context' . . . class A extends PureComponent { render() { const { bbb } = this.props return ( <div> <tryContext.Provider value={bbb}> <tryContext.Consumer> {state1 => <div className="try">{state1}</div>} </tryContext.Consumer> </tryContext.Provider> <tryContext.Provider value={'BBBBBB'}> <B /> </tryContext.Provider> </div> ) } } class B extends PureComponent { static contextType = tryContext render() { return <div>{this.context}</div> } } //B.contextType = tryContext
//父组件A class A extends React.Component { getChildContext() { return { color: 'red' } } } A.childContextTypes = { color: PropTypes.string }
//子组件B class B extends React.Component { render() { return <p>{this.context.color}</p> } } B.contextTypes = { color: PropTypes.string }
####老版弊端
####新版注意点
参考文献 官网 头条技术博客 简书
The text was updated successfully, but these errors were encountered:
No branches or pull requests
React.createContext
使用
新老对比
老版
新老对比
####老版弊端
子组件 B 执行 shouldComponetUpdate,由于组件 B 自身并不依赖 Context,所以 shouldComponetUpdate 检测到 state 与 prop 均未变化因此返回 false。无需重新 render。
####新版注意点
The text was updated successfully, but these errors were encountered: