通常情況下媒怯,在react組件中订讼,我們可以通過(guò)props很清楚的知道哪些數(shù)據(jù)被傳遞,但是在一些特定的場(chǎng)景下扇苞,我們不想要手動(dòng)的向下每一層傳遞我們需要的props欺殿,這就需要用到強(qiáng)大的context API了。
首先是一個(gè)不使用context的例子:
這里使用了this.props.children鳖敷,所有嵌套在組件中的 JSX 結(jié)構(gòu)都可以在組件內(nèi)部通過(guò) props.children 獲取到:
import React from 'react';
export class Button extends React.Component {
render() {
return (
<button style={{background: this.props.color}}>
{this.props.children}
</button>
);
}
}
export class Message extends React.Component {
render() {
return (
<div>
<Button color={this.props.color}>Delete</Button>
</div>
);
}
}
export class MessageList extends React.Component {
render() {
const color = "purple";
return (
<Message color={color} />
)
}
}
然后修改為使用context:
import React from 'react';
import PropTypes from 'prop-types';
export class Button extends React.Component {
render() {
return (
<button style={{ background: this.context.color }}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: PropTypes.string
};
export class Message extends React.Component {
render() {
return (
<div>
<Button >Delete</Button>
</div>
);
}
}
export class MessageList extends React.Component {
getChildContext() {
return { color: "purple" };
}
render() {
return (
<Message />
)
}
}
MessageList.childContextTypes = {
color: PropTypes.string
};
通過(guò)在MessageList(context提供者)中添加childContextTypes和getChildContext脖苏,React會(huì)向下自動(dòng)傳遞參數(shù),任何組件只要在它的子組件中(這個(gè)例子中是Button)定踱,就能通過(guò)定義contextTypes來(lái)獲取參數(shù)棍潘。
如果contextTypes沒有定義,那么context將會(huì)是個(gè)空對(duì)象。