目录
Context api before React v16.3
New Context API 的实践
| 名称 | 链接 | 备注 |
| new context api | 英文 | |
| 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: React 的‘上下文’,贯穿了整个React,不需要层层传递。
- 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() {
- // 动态值state
- const { 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: '默认文案',
- };