react学习四-context

2020-08-05  本文已影响0人  梦行乌托邦

AppContext.js

import React from 'react';

export const Context = React.createContext();
export const Provider = Context.Provider;
export const Consumer = Context.Consumer;

Parent0.js

import React from 'react';
import Parent1 from './Parent1';

import {Provider} from './AppContext';

const store = {
    home: {},
    user: {
        name: 'lili'
    }
}

function Parent0(){
    return (
        <div>
            <Provider value={store}>
                <Parent1 />
            </Provider>
        </div>
    );
}

export default Parent0;

Parent1.js

import React, { Component } from 'react';
import Parent2 from './Parent2';

class Parent1 extends Component {
    render() { 
        console.log('Parent1', this.props);
        return ( 
            <div>
                <Parent2 />
            </div>
         );
    }
}
 
export default Parent1;

Parent2.js

import React from 'react';
import { Consumer } from './AppContext';
import Parent3 from './Parent3';

export default function Parent2(props) {
    console.log('Parent2', props);
    return (
        <div>
            <Consumer>
                {ctx => <Parent3 {...ctx} />}
            </Consumer>
        </div>
    );
}

Parent3.js

import React from 'react';

export default function Parent3(props) {
    console.log('Parent3', props);
    return (
        <div>
            Parent3
        </div>
    );
}

组件关系:
Parent0 -》 Parent1 -》 Parent2 -》 Parent3
Parent0中的store通过context的方式传递到了Parent3!

通过Consumer包围的组件(Parent3)
可以使用
提供了Provider的组件中的数据(Parent0)

不同数据用不同的Provider和Consumer

上一篇 下一篇

猜你喜欢

热点阅读