React context
介绍Contexts 是React的一个重要属性,但是到目前为止,这个属性在正式的文档里面还没有对它进行正式介绍,在 reactv0.1.4将会正式发布这个属性。下面先来介绍一下它的使用方式。 React.withContext
var A = React.createClass({ contextTypes: { name: React.PropTypes.string.isRequired,},render: function() { return <div>My name is: {this.context.name}</div>; } }); React.withContext({'name': 'Jonas'},function () { // Outputs: "My name is: Jonas" React.render(<A />,document.body); }); 任何想访问context里面的属性的组件都必须显式的指定一个 如果你为一个组件指定了context,那么这个组件的子组件只要定义了contextTypes 属性,就可以访问到父组件指定的context了。 var A = React.createClass({ render: function() { return <B />; } }); var B = React.createClass({ contextTypes: { name: React.PropTypes.string },function () { React.render(<A />,document.body); }); 为了减少文件的引用,你可以为 var ContextMixin = { contextTypes: { name: React.PropTypes.string.isRequired },getName: function() { return this.context.name; } }; var A = React.createClass({ mixins: [ContextMixin],render: function() { return <div>My name is {this.getName()}</div>; } }); React.withContext({'name': 'Jonas'},document.body); }); getChildContext和访问context 的属性是需要通过 // This code *does NOT work* becasue of a missing property from childContextTypes var A = React.createClass({ childContextTypes: { // fruit is not specified,and so it will not be sent to the children of A name: React.PropTypes.string.isRequired },getChildContext: function() { return { name: "Jonas",fruit: "Banana" }; },render: function() { return <B />; } }); var B = React.createClass({ contextTypes: { fruit: React.PropTypes.string.isRequired },render: function() { return <div>My favorite fruit is: {this.context.fruit}</div>; } }); // Errors: Invariant Violation: A.getChildContext(): key "fruit" is not defined in childContextTypes. React.render(<A />,document.body); 假设你的应用程序有多层的context。通过 var A = React.createClass({ childContextTypes: { fruit: React.PropTypes.string.isRequired },getChildContext: function() { return { fruit: "Banana" }; },render: function() { return <B />; } }); var B = React.createClass({ contextTypes: { name: React.PropTypes.string.isRequired,fruit: React.PropTypes.string.isRequired },render: function() { return <div>My name is: {this.context.name} and my favorite fruit is: {this.context.fruit}</div>; } }); React.withContext({'name': 'Jonas'},function () { // Outputs: "My name is: Jonas and my favorite fruit is: Banana" React.render(<A />,document.body); }); context 是就近引用的,如果你通过 var A = React.createClass({ childContextTypes: { name: React.PropTypes.string.isRequired },getChildContext: function() { return { name: "Sally" }; },render: function() { return <B />; } }); var B = React.createClass({ contextTypes: { name: React.PropTypes.string.isRequired },function () { // Outputs: "My name is: Sally" React.render(<A />,document.body); }); 总结通过context传递属性的方式可以大量减少 通过显式的通过 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |