假設(shè)有層級(jí) A->B->C->D,如果A需要傳遞一個(gè)參數(shù)給D,根據(jù)前文的知識(shí),只能通過(guò)props參數(shù)一層一層傳遞。
有沒(méi)有更便捷的方法呢?React提供了context機(jī)制來(lái)解決這個(gè)問(wèn)題。
context涉及到父級(jí)(發(fā)送方)和子級(jí)(接收方),父級(jí)設(shè)置context,子級(jí)讀取context。
我們先來(lái)看一下父級(jí)的一個(gè)實(shí)現(xiàn):
class MessageList extends React.Component {
getChildContext() {
return {color: "purple"};
} // 此具返回childContext具體值
render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
}
MessageList.childContextTypes = { // 通過(guò)childContextTypes定義context中變量類型
color: PropTypes.string
};
父級(jí)通過(guò)childContextType來(lái)定義context中的類型,以及通過(guò)getChildContext來(lái)返回context的具體value。
再來(lái)看一下子級(jí)如何獲取父級(jí)設(shè)置的context:
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}> // 使用context
{this.props.children}
</button>
);
}
}
Button.contextTypes = { // 定義接收context
color: PropTypes.string
};
子級(jí)通過(guò)contextTypes來(lái)標(biāo)識(shí)自己接收context,然后就能直接使用context了。
如果子級(jí)沒(méi)有定義contextTypes,則context對(duì)象將為空。另外,如果定義了contextTypes,以下回調(diào)中都會(huì)添加一個(gè)新參數(shù)context參數(shù):
constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)
最后,函數(shù)式組件中,通過(guò)定義contextType也能使用context:
const PropTypes = require('prop-types');
const Button = ({children}, context) =>
<button style={{background: context.color}}>
{children}
</button>;
Button.contextTypes = {color: PropTypes.string};
因?yàn)楹瘮?shù)式組件不支持state、ref,一般不建議使用函數(shù)式組件。
想學(xué)計(jì)算機(jī)技術(shù)嗎?需要1對(duì)1專業(yè)級(jí)導(dǎo)師指導(dǎo)嗎?想要團(tuán)隊(duì)陪你一起進(jìn)步嗎?歡迎加我為好友!微信號(hào):iTekka。