React 中 context 的使用
原文引自个人博客 [走啊走的记录] - React 中 context 的使用官方文档说明(英) 看了别人写的中文博客,再看了官方英文文档,发现还是官方文档讲的浅显易懂一些,看了之后,半翻译半理解地写了这篇博客,更易于新手理解。 介绍 使用 Context 的原因 为了有时候想传递数据通过组件树,但是不想给每一层级的组件手动传递属性,那么 有时候 官方文档的示例代码如下 var Button = React.createClass({
render: function() {
return (
<button style={{background: this.props.color}}> {this.props.children} </button>
);
}
});
var Message = React.createClass({
render: div> {this.props.text} <Button color={this.props.color}>Delete</Button> </div>
);
}
});
var MessageList = React.createClass({
render: var color = "purple";
var children = this.props.messages.map(function(message) {
return <Message text={message.text} color={color} />; }); return <div>{children}</div>; } });
使用 context 改进数据传递 现在我们使用 var Button = React.createClass({
// 必须指定context的数据类型
contextTypes: {
color: React.PropTypes.string
},render: {{background: this.context.color}}> {this.props.children} </Button>Delete</var MessageList = React.createClass({
//
childContextTypes: {
color: React.PropTypes.string
},getChildContext: return {color: "purple"};
},0)">{message.text} />; }); return <div>; } });
示例代码中通过添加 总结 指定数据并要将数据传递下去的父组件要定义 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |