Use context to transmit data across the component tree in react

Source: Internet
Author: User

--------------------------------- Description 1

Original: 78480758

 

Note: Since react v15.5, the react. proptypes helper function has been discarded. We recommend that you use the prop-types library to define contexttypes.
2.1 first, you need to install a third-party package named prop-types through NPM install prop-types on the terminal.

Getchildcontext is defined in the parent component, which indicates the information that can be used by the Child component.
Childcontexttypes is defined in the parent component. The attributes passed by getchildcontext to the child component must be specified through childcontexttypes. Otherwise, an error will occur.
Child components must specify the elements to be accessed through contexttypes. Contexttypes is not defined. context is an empty object.

Parent component Definition

class Greeter extends Component{
    constructor(props){
        super(props) this.state={
            add:87,
            remove:88 }
    }
    static childContextTypes = {
        add:T.number,
        remove:T.number
    }
    getChildContext() {
       const { add,remove} = this.state; return {
           add,
           remove
       }
    }
    render(){ return( <div>
                <ComponetReflux/>
            </div>  )
    }
}

Sub-component Definition

class ComponetReflux extends Component {
     constructor (props) {
         super (props)
         this.state = {
            
         }
     }
     static contextTypes = {
         add: T.number,
         remove: T.number
     }
     render () {
         console.log (this.context) // print {add: 87, remove: 88}
         const {name, age} = this.state
         return (
             <div> test context </ div>
     )
     }
};

 

 

----------------------------------------------------------------- Description 2

Original: 77715862

 

React honors one-way data streams and transfers data from top to bottom. However, communication between lower-level components or components not on one data stream becomes more complex. There are many ways to solve the communication problem. If there is only a parent-child relationship, the parent can pass a callback function as an attribute to the child level. The child level can directly call the function to communicate with the parent level.

The Component Hierarchy Is nested to a relatively deep level. You can use the context getchildcontext to transmit information. In this way, you do not need to upload functions layer by layer. sub-levels of any layer can be directly accessed through this. context.

Sibling components cannot communicate directly. They can only use superiors on the same layer as transfer stations. If the sibling components are the top-level components, in order to allow them to communicate, they must have another layer of components on their outer layers. This layer of components stores data and transmits information, this is what Redux does.

Information between components can also be transmitted through global events. Different pages can pass data through parameters, and the next page can be obtained using location. Param. In fact, react itself is very simple, but it is difficult to implement data exchange between components elegantly and efficiently.

Today, let's get familiar with the context data transmission of react.
 

 

If context is not used to transmit data, we can refer to react's document: context, which is passed down through the Component Attribute Level 1. this method is troublesome. If the component tree is deep, unnecessary attributes must be introduced to nodes on each path. define the root component of Context
import React from ‘react’;
 
# After React 15.5, use of PropTypes requires the introduction of external libraries. Using React.PropTypes directly will throw a warning
import PropTypes from ‘prop-types’;
 
# React Router V4 version needs to import the required components from react-router-dom
import {Route, Link} from ‘react-router-dom’;
 
import {Row, Col, Menu, Icon, Dropdown, Layout} from ‘antd’;
const {Sider, Content} = Layout;
 
import UserList from ‘./UserList’;
import UserDetail from ‘./UserDetail’;
import Sidebar from ‘../_layouts/Sidebar’;
 
const avatars = [
  "elyse.png",
  "kristy.png",
  "matthew.png",
];
 
const data = [];
for (let i = 0; i <= avatars.length; i ++) {
  data.push ({key: i, name: ‘Hu Yanzu 3’, age: 42, address: ‘No. 1 Hudi Park, West Lake District’);
}
const columns = [
  {title: ‘ID’, dataIndex: ‘key’, key: ‘key’},
  {title: ‘name’, dataIndex: ‘name’, key: ‘name’, render: function (text, record, index) {
    return (<Link to = {`/ users / $ {index}`}> <div style = ({display: ‘block‘}}> {text} </ div> </ Link>)
  }},
  {title: ‘Age’, dataIndex: ‘age’, key: ‘age’},
  {title: ‘Address’, dataIndex: ‘address’, key: ‘address’},
  {
    title: ‘Action’,
    key: ‘action’,
    render: function (text, record, index) {
      return (
        <span>
          <a> <Icon type = "plus" /> </a>
          <span className = "ant-divider" />
          <a> <Icon type = "close" /> </a>
        </ span>
      )
    }
  }
];
 
class UserIndex extends React.Component {
  constructor (props) {
    super (props)
  }
 
  # Define the methods that Context needs to implement
 
  getChildContext () {
    return {
      data: data,
      columns: columns
    };
  }
  render () {
    return (
      <Layout>
        <Sider>
          <div id = "user-side-bar" className = "side-bar">
          <Sidebar />
          </ div>
        </ Sider>
        <Content>
          <h2 className = "pagetitle"> User Information Page </ h2>
          <Row gutter = (16}>
            <Col span = {16}>
              <UserList />
            </ Col>
            <Col span = {4}>
              <Route path = {`$ {this.props.match.url} /: id`} component = {UserDetail} />
            </ Col>
          </ Row>
        </ Content>
      </ Layout>
    )
  }
}
 
# Declare the Context type
 
UserIndex.childContextTypes = {
  data: PropTypes.array,
  columns: PropTypes.array,
};
 
export default UserIndex;
Intermediate component

In the middle, it is no longer passed down through the first-level Attribute of the component.render()Define an empty<List/>:

 

import { Table, Icon } from ‘antd‘;
 
import {
  Link
} from ‘react-router-dom‘;
 
import List from ‘../_common/List‘;
 
class UserList extends React.Component {
  constructor(props){
    super(props)
  }
  render(){ return ( <div>
        <List />
      </div>  )
  }
}
 
export default UserList;
Child components, list
import React from ‘react’;
import PropTypes from ‘prop-types’;
import {Layout, Table} from ‘antd’;
const {Sider, Content} = Layout;
class List extends React.Component {
   constructor (props) {
     super (props);
   }
 
   render () {
     return (
       <Content>
         <Table columns = {this.context.columns} dataSource = {this.context.data} size = "middle" />
       </ Content>
     );
   }
}
 
List.propTypes = {
     data: PropTypes.array,
     columns: PropTypes.array
};
 
# Declare contextTypes here to access the Context data defined in the UserIndex component.
 
List.contextTypes = {
   data: PropTypes.array,
   columns: PropTypes.array
};
 
export default List; 

 

In this way, we can obtain the data of the parent component from the child component, regardless of the number of layers.

 

Use context to transmit data across the component tree in react

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.