目录
扩展学习资料
Context api before React v16.3
Context
实战使用-Context
Context VS Props
Context
Props
Context的缺陷
New Context API 的实践
扩展学习资料
名称 | 链接 | 备注 |
new context api | https://reactjs.org/docs/context.html | 英文 |
old context api | https://5abc31d8be40f1556f06c4be--reactjs.netlify.app/docs/context.html | |
context api 问题 | https://medium.com/@gobindathakur/problems-with-previous-react-context-api-317b247d78d4 | 英文 |
Context api before React v16.3
官方说:功能强大,但是不推荐使用
Context
Context: React 的‘上下文’,贯穿了整个React,不需要层层传递。
- childContextTypes 父级组件定义,声明Context对象属性。【定义属性】
- getChildContext 父级组件定义,返回Context对象,方法名是约定的。【属性赋值】
- contextTypes 在任意层级的子级组件中定义,就可以在子级组件使用context。【子级使用】
实战使用-Context
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CustomButton from './components/customButton';
// 父组件
export default class Home extends Component {// 定义类型static childContextTypes = {color: PropTypes.string, }constructor(props) {super(props);this.state = {color: '#28a745', }; }// 属性赋值getChildContext() {// 动态值stateconst { color } = this.state;return {color, } }render() {return (<div><CustomButton>React Context Demo</CustomButton></div>);}
}
// 子组件
export default function CustomButton(props, context) {const { color } = context;const { children } = props;return (<button type="button" style={{ color }}>{ children }</button> );
}
// 定义context类型
CustomButton.contextTypes = {color: PropTypes.string,
}
CustomButton.propTypes = {children: PropTypes.string,
};
CustomButton.defaultProps = {children: '默认文案',
};
Context VS Props
Context
- 父级(根节点)与应用节点都需要强制类型声明,关键字不一样。
- 全局上下文,贯穿了整个应用。
Props
- 应用节点需要类型声明,非强制。
- 只能进行逐级传递,一旦中间断掉,就会传递失败。
Context的缺陷
- setState()时,getChildContext()也会触发。父级组件的shouldComponentUpdate返回false,就会不执行getChildContext(),引起更新失败。导致子组件接收到的context还是老的,破坏了传递流程。
- PureComponent或者自定义的优化可能接收不到Context的更新。