A component can use the getChildContext method to return an object that is the context of the subtree. The component providing the context must provide childContextTypes as the declaration and validation of the context.

If a component sets the context, its children can access the contents directly, like global variables in the subtree at the root of the component.

Child components of any depth can use contextTypes to declare which states you want in the context, and then access those states through this.context.

Context breaks the convention of components passing data between components through props, greatly enhancing the coupling between components. And, just like global variables, the data in the context can be touched and modified at will, and each component can change the contents of the context, causing the program to behave unpredictably.

But this mechanism is useful for front-end application state management, because a lot of state is shared between components,

Context is going to be very convenient for us. Some third-party front-end application state management libraries (such as Redux) take full advantage of this mechanism to provide convenient state management services. But you don’t need to write the context manually, you don’t need to use it, you just need to use these third-party application state management libraries.

<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8" />
<title>React Context (Without using props, the parent passes information to the child component)</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.1/prop-types.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Title extends React.Component {
  static contextTypes = {
    themeColor: PropTypes.string
  }

  render () {
    return (
      <h1 style={{ color: this.context.themeColor}} >xutongbao</h1>)}}class Header extends React.Component {
  render () {
    return (
    <div>
      <h2>header</h2>
      <Title />
    </div>)}}class Index extends React.Component {
  static childContextTypes = {
    themeColor: PropTypes.string
  }

  constructor () {
    super(a)this.state = { themeColor: 'red' }
  }

  getChildContext () {
    return { themeColor: this.state.themeColor }
  }

  render () {
    return (
      <div>
        <Header />
      </div>
    )
  }
}
ReactDOM.render(
  <Index />.document.getElementById('root'));</script>
</body>
</html>
Copy the code