在使用redux的过程中,我们在根组件注入store,然后想在所有的下级组件(包括子组件,孙组件……)去使用store,其中最容易想到的办法就是,将store从根组件一级一级向下传递,OK这种办法可以实现,但是对于嵌套了多级的组件来说,就显得有些麻烦了,比如根组件的第五级组件需要使用store去dispatch一个action,那么中间每一个组件都要传递store到下一级,即使他们并不需要使用.
那么有没有一种像是全局变量这种的方案呢,当然有, 就是 context 这个API
下面通过官网的例子讲解使用
1.这个为”一级一级向下传递的解决方案”
javascript 代码
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Button extends React.Component {
render() {
return (
<button style={{background: this.props.color}}>
{this.props.children}
</button>
);
}
}
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button color={this.props.color}>Delete</Button>
</div>
);
}
}
class MessageList extends React.Component {
render() {
const color = "purple";
const children = this.props.messages.map((message) =>
<Message text={message.text} color={color} />
);
return <div>{children}</div>;
}
}
2.这个为context的解决方案
javascript 代码
import React, { Component } from 'react';
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
};
getChildContext就是你希望向下级组件传递的东西,它用于根组件
childContextTypes 声明子组件作用域的类型,用于根组件
contextTypes 表明子组件的作用域类型,这与 childContextTypes 相当于一个接口暗号,如果对上了,OK就可以使用根组件传过来的东西了.