Skip to content

context的使用

司徒正美 edited this page Mar 7, 2017 · 4 revisions

context只传递一层

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src='./dist/jsx-parser.js'></script>
    <script src='./dist/evalJSX.js'></script>
    <script src='./dist/anu.js'></script>
    <script>
    

        var Parent = anu.createClass({
          

            render: function() {
                return evalJSX(`
    	<div id="333">
        {this.context.value}
      </div>`, {
                    this: this
                });
            }
        });

        var App = anu.createClass({
            getChildContext: function() {
                return {
                    value: '6666'
                };
            },
            render: function() {
                return evalJSX(`
      <Parent/>`, {
                    this: this,
                    Parent: Parent
                });
            }
        });

        window.onload = function() {
            var result = anu.render(anu.createElement(App), document.body)
            console.log(result)
        }
    </script>
</head>

<body>
    <div>这个默认会被清掉</div>
</body>

</html>

传递多层

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src='./dist/jsx-parser.js'></script>
    <script src='./dist/evalJSX.js'></script>
    <script src='./dist/anu.js'></script>
    <script>
        var Children = anu.createClass({

            render: function() {
                return evalJSX(`<span>{this.context.papa || '并没有context'}</span>`, {
                    this: this
                })
            }
        });


        var Parent = anu.createClass({
            getChildContext: function() {
                return {
                    papa: 'papa'
                };
            },

            render: function() {
                return evalJSX(`
    	<div class="parent">{this.props.children}</div>`, {
                    this: this
                });
            }
        });

        var App = anu.createClass({
            getChildContext: function() {
                return {
                    value: '6666'
                };
            },
            render: function() {
                return evalJSX(`
      <Parent><Children/></Parent>`, {
                    this: this,
                    Children: Children,
                    Parent: Parent
                });
            }
        });

        window.onload = function() {
            var result = anu.render(anu.createElement(App), document.body)
            console.log(result)
        }
    </script>
</head>

<body>

    <div>这个默认会被清掉</div>
</body>

</html>