美文网首页
React组件化(一) Context 跨层级通讯

React组件化(一) Context 跨层级通讯

作者: key君 | 来源:发表于2019-10-30 10:54 被阅读0次

组件化优点:
1.增强代码重用性,提高开发效率
2.简化调试步骤,提升整个项目的可维护性
3.便于协同开发

创建项目:

npx create-react-app lesson2

进入项目目录:

cd lesson2

启动项目:

npm start

Context 跨层级通讯

App.js

import React from 'react';
import HomePage from './pages/HomePage';
import {Provider,Consumer} from "./AppContext"
import { from } from 'rxjs';
// //跨层级通讯  Provider Consumer是组件
// const Context = React.createContext();
// const Provider = Context.Provider;
// const Consumer = Context.Consumer;

function Child(props){
  return (
  <div>
    <p>{props.user.name}</p>
  </div>
  );
}

const store = {
  user: {
    name: '娜扎',
  }
}

function App() {
  return (
    <div className="App">
      <Child {...store}/>
      <Provider value={store}>
        <Consumer>
          {
            ctx => <Child {...ctx}/>
          }
        </Consumer>
        {/* <Consumer>
          {
            ctx => <HomePage {...ctx}/>
          }
        </Consumer> */}
        <HomePage/>
      </Provider>
    </div>
  );
}

export default App;

创建AppContext.js

import React from "react";
//跨层级通讯  Provider Consumer是组件
export const Context = React.createContext();
export const Provider = Context.Provider;
export const Consumer = Context.Consumer;

创建pages/HomePage.js

import React, { Component } from 'react'
import { Consumer } from '../AppContext';
import TopBar from '../components/TopBar';

export default class HomePage extends Component {
    render() {
        console.log(this.props);
        return (
            <div>
                <TopBar/>
                HomePage
                <Consumer>
                    {
                        ctx=><div>{ctx.user.name}</div>
                    }
                </Consumer>
            </div>
        )
    }
}

创建components/TopBar.js

import React, { Component } from 'react'
import { Consumer } from '../AppContext'

export default class TopBar extends Component {
    render() {
        return (
            <Consumer>
                {
                    ctx => <TopBarHandle {...ctx}/>
                }
            </Consumer>
        )
    }
}

function TopBarHandle(props){
    return (<div className="tabBar">
        {props.user.name}
    </div>)
}

相关文章

网友评论

      本文标题:React组件化(一) Context 跨层级通讯

      本文链接:https://www.haomeiwen.com/subject/ipanvctx.html