React之使用context传递数据

react中当要从父组件给子孙组件传递数据时 如果用props传递 则需要一级一级传递 而如果用context时 则可以在父组件中加入getChildContext函数 并声明需要传递的数据 在需要接受到数据的组件中声明变量类型Test.contextTypes = {test : PropTypes.string} 

Example:

//父组件
import React, { Component,PropTypes } from 'react';
import Son from './Son';
 
class App extends Component {
 
  getChildContext() {
      return {test: "hello"};
  }
 
  render() {
      return (
          

父组件

); } } App.childContextTypes = { test: PropTypes.string }; export default App;
//子组件
import React, { Component,PropTypes } from 'react';
import Grands

你可能感兴趣的:(react,react)