react context跨组件传递信息

从腾讯课堂看到的一则跨组件传递数据的方法,贴代码:

使用步骤:

1.在产生参数的最顶级组建中,使用childContextTypes静态属性来定义需要放入全局参数的类型

2.在父组件中,提供状态,管理数据,

3.声明子组件获取全局参数的方式

4.在子组件中,使用contextTypes静态属性,生命需要获取父组件放入全局context中的数据类型

5.在子组件需要的地方获取全局参数

父组件:
import React, { Component } from 'react'; import logo from './logo.svg'; import PropTypes from 'prop-types'; import Screen from './components/screen/Screen'; import ControlPanel from './components/control/ControlPanel'; import './assets/styles/core.css'; class App extends Component { // 1.在产生参数的最顶级组建中,使用childContextTypes静态属性来定义需要放入全局参数的类型 static childContextTypes = { title: PropTypes.string, play: PropTypes.string, stop: PropTypes.string } // 2.在父组件中,提供状态,管理数据, state = { title: '少女时代', play: '播放', stop: '暂停' } //3.声明子组件获取全局参数的方式 getChildContext() { return { title: this.state.title, play: this.state.play, stop: this.state.stop } } render() { return ( <div className="itsource-tv"> <Screen /> <ControlPanel /> </div> ); } } export default App;

子组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TVInfo from './Tvinfo'

class Screen extends Component {
  render() {
    return (
      <TVInfo />
    );
  }
}

export default Screen;

孙组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './ty-info.css';

class TVInfo extends Component {
    static contextTypes = {
        title: PropTypes.string
    }
  render() {
    return (
      <div className="TVInfo">
       {this.context.title}
      </div>
    );
  }
}

export default TVInfo;