使用react过程中,经常有深层组件需要祖先组件的数据,但是中间层组件又不需要care这些数据,所以层级传递数据显得啰嗦,当然使用redux的话可以很明确的解决这个问题,本文讲述在不使用状态管理机的情况下的react的解决方法之——contex
。并且在v16.3
的react也会正式推出context
的使用。
import PropTypes from 'prop-types';
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: 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: PropTypes.string
};
const MyContext = React.createContext({
name: 'context'
})
class MyName extends React.component {
render() {
return(
<MyContext.Consumer>
{
context => {
<p>{context.name}</p>
}
}
</MyContext.Consumer>
)
}
}
class App extends React.component {
render() {
return (
<MyContext.Provider value={name: 'darren'}>
<MyName />
</MyContext.Provider>
)
}
}