美文网首页
八、context

八、context

作者: 懒羊羊3号 | 来源:发表于2019-01-10 17:02 被阅读0次

    旧版

    import React from 'react';
    import ReactDOM from 'react-dom';
    const Component = React.PureComponent;
    class Index extends Component {
        static childContextTypes = {
            themeColor: '',
        }
        constructor () {
            super()
            this.state = { themeColor: 'red' }
        }
        getChildContext () {
            return { themeColor: this.state.themeColor }
        }
        render () {
            return (
                <div>
                    <Header />
                    <Main />
                </div>
            )
        }
    }
    
    class Header extends Component {
        render () {
            return (
                <div>
                    <h2>This is header</h2>
                    <Title />
                </div>
            )
        }
    }
    class Title extends Component {
        static contextTypes = {
            themeColor: '',
        }
        render () {
            return (
                <h1 style={{color: this.context.themeColor}}>React.js 小书标题</h1>
            )
        }
    }
    
    ReactDOM.render(
        <Index />,
        document.getElementById('root')
    )
    
    

    新版

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const ThemeContext = React.createContext({
        background: '',
        color: ''
    });
    
    class Index extends React.Component {
        render () {
            return (
                <ThemeContext.Provider value={{background: 'green', color: 'red'}}>
                    <Header />
                </ThemeContext.Provider>
            );
        }
    }
    
    class Header extends React.Component {
        render () {
            return (
                <Title>Hello React Context API</Title>
            );
        }
    }
    
    class Title extends React.Component {
        render () {
            return (
                <ThemeContext.Consumer>
                    {context => (
                        <h1 style={{background: context.background, color: context.color}}>
                            {this.props.children}
                        </h1>
                    )}
                </ThemeContext.Consumer>
            );
        }
    }
    
    ReactDOM.render(
        <Index />,
        document.getElementById('root')
    )
    

    相关文章

      网友评论

          本文标题:八、context

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