我們都知道,在React中數據可以以流的形式自上而下的傳遞,當你使用組件的時候,你可以看到組件的props屬性會自上而下傳遞。但是在有些情況下不想通過父組件的props屬性一級一級的向下傳遞,而是希望在某一子級中直接得到上N級父組件的props中的值。那么接下來就讓我們看一下通過props傳值和context傳值的情況
1、通過props傳值
class Button extends React.Component {
render() {
return (
<button style={{background: this.props.color}}>
{this.props.children}
</button>
);
}
}
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button color={this.props.color}>Delete</Button>
</div>
);
}
}
class MessageList extends React.Component {
render() {
const color = "purple";
const children = this.props.messages.map((message) =>
<Message text={message.text} color={color} />
);
return <div>{children}</div>;
}
}
過程解析:
(1)代碼結構大致分為3級:頂層MessageList、Message一級子類和Button底層子類
(2)從父組件到子組件的傳值情況——text:在頂層組件MessageList中的值,傳遞到一級子組件Message中,并在此組件中被使用{this.props.text}
(3)從父組件到子組件的傳值情況——color:頂層組件MessageList中的值,先傳遞到一級子組件Message中,在傳遞到二級子組件Button中,最后在二級子組件中被使用{this.props.color}
(4)總結:從上邊分析可以看出,通過props屬性進行父子組件的傳值是一級一級的向下傳遞的
2、通過context進行值得越級傳遞
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: React.PropTypes.string
};
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
}
class MessageList extends React.Component {
getChildContext() {
return {color: "purple"};
}
render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
}
MessageList.childContextTypes = {
color: React.PropTypes.string
};
過程解析:通過添加childContextTypes和getChildContext()到MessageList(context的提供者),React自動向下傳遞數據然后在組件樹中的任意組件(也就是說任意子組件,在上面的例子中就是Button)都能通過定義contextTypes訪問context中的數據。
(1)在頂層組件MessageList中定義了頂層組件所擁有的子類context對象——該頂層組件所擁有的子類context對象為color,且必須為字符串,代碼如下:
MessageList.childContextTypes = {
color: React.PropTypes.string
};
(2)通過getChldText方法,來給子context對象的屬性賦值,這樣就完成了頂層組件中,context組件的賦值,代碼如下:
getChildContext() {
return {color: "purple"};
}
(3)越級傳遞。因為color屬性只在最底層使用(在一級子組件Message中并沒有直接用到),因此可以直接傳遞到最底層(越級),在Button組件中使用。首先在Button組件中,再次說聲明了所接受到的context的子組件color的類型,聲明必須為字符串,代碼如下:
Button.contextTypes = {
color: React.PropTypes.string
};
(4)最后通過this.context.color這種方式調用,這樣就通過Context實現了組件之間的越級傳值,代碼如下:
<button style={{background: this.context.color}}>
{this.props.children}
</button>