假設(shè)有層級 A->B->C->D皿曲,如果A需要傳遞一個參數(shù)給D蔬将,根據(jù)前文的知識匕累,只能通過props參數(shù)一層一層傳遞。
有沒有更便捷的方法呢迂求?React提供了context機制來解決這個問題碾盐。
context涉及到父級(發(fā)送方)和子級(接收方),父級設(shè)置context揩局,子級讀取context毫玖。
我們先來看一下父級的一個實現(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 = { // 通過childContextTypes定義context中變量類型
color: PropTypes.string
};
父級通過childContextType來定義context中的類型,以及通過getChildContext來返回context的具體value凌盯。
再來看一下子級如何獲取父級設(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
};
子級通過contextTypes來標(biāo)識自己接收context付枫,然后就能直接使用context了。
如果子級沒有定義contextTypes驰怎,則context對象將為空阐滩。另外,如果定義了contextTypes县忌,以下回調(diào)中都會添加一個新參數(shù)context參數(shù):
constructor(props, context)
componentWillReceiveProps(nextProps, nextContext)
shouldComponentUpdate(nextProps, nextState, nextContext)
componentWillUpdate(nextProps, nextState, nextContext)
componentDidUpdate(prevProps, prevState, prevContext)
最后掂榔,函數(shù)式組件中,通過定義contextType也能使用context:
const PropTypes = require('prop-types');
const Button = ({children}, context) =>
<button style={{background: context.color}}>
{children}
</button>;
Button.contextTypes = {color: PropTypes.string};
因為函數(shù)式組件不支持state芹枷、ref衅疙,一般不建議使用函數(shù)式組件。
想學(xué)計算機技術(shù)嗎鸳慈?需要1對1專業(yè)級導(dǎo)師指導(dǎo)嗎饱溢?想要團隊陪你一起進步嗎?歡迎加我為好友!微信號:iTekka走芋。