context的作用
context 通過組件數(shù)提供了一個傳遞數(shù)據(jù)的方法,從而避免了在每一個層級手動的傳遞 props 屬性。
在一個典型的 React 應(yīng)用中,數(shù)據(jù)是通過 props 屬性由上向下(由父及子)的進(jìn)行傳遞的,但這對于某些類型的屬性而言是極其繁瑣的(例如:地區(qū)偏好,UI主題),這是應(yīng)用程序中許多組件都所需要的。 Context 提供了一種在組件之間共享此類值的方式,而不必通過組件樹的每個層級顯式地傳遞 props 。
在react中實(shí)現(xiàn)context的使用
//使用context中值的組件
import React from 'react';
import PropTypes from 'prop-types';
class Button extends React.Component {
render() {
return (
// context中的值具體的使用
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: PropTypes.string
};
// 中間的組件
import React from 'react';
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
}
// 頂級組件,在配置context的值
import React from 'react';
import PropTypes from 'prop-types';
class MessageList extends React.Component {
getChildContext() {
// 設(shè)置context中color的具體值
return {color: "purple"};
}
render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
}
MessageList.childContextTypes = {
// 指定context中存在color,對應(yīng)的值為字符串類型
color: PropTypes.string
};