Skip to content

context的使用

司徒正美 edited this page May 19, 2017 · 4 revisions

props只能往下传递一层,context可以往下传递许多层

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
   
    <script src='./dist/React.js'></script>
    <script src="./test/babel.js"></script>
    <script type='text/babel'>
  
        class Parent extends React.Component{
        
            render() {
    	       return (<div className="parent"><Son /></div>)
            }
        }
       class Son extends React.Component{
        
            render() {
    	       return (<div className="son"> {this.context.value} </div>)
            }
        }

       class App extends React.Component{
            getChildContext() {
                return {
                    value: 666
                };
            }
            render() {
    	       return (<div className='app'><Parent /></div>)
            }
        };


        window.onload = function() {
            ReactDOM.render(<App />, document.getElementById('example'));
        }
    </script>
</head>

<body>
    <div id='example'>这个默认会被清掉</div>
</body>

</html>