zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    shell-3
    shell-2
    shell-1
    zabbix监控top
    django指导网址
    文件下载漏洞
    Build a Raspberry Pi powered live train station sign for your desk
    Use a Raspberry Pi to communicate with Amazon AWS IoT
    Describing and Listing Your Stacks
    固有功能参考 Intrinsic Function Reference
  • 原文地址:https://www.cnblogs.com/xuyan1/p/9757353.html
Copyright © 2011-2022 走看看