资源: https://medium.com/dailyjs/reacts-%EF%B8%8F-new-context-api-70c9fe01596b
尽管官方文档不建议使用 context, 但是 react-redux 等库都在使用 context 属性
-
context nested
可以通过 “react-composer” 简化nest逻辑
资源:https://reactjs.org/docs/context.html
- 分享 context 组件:
- getChildContext() //返回context内容
- childContextTypes // 定义分享的 context的属性
- 获取 context 组件:
- this.context.xxx // 使用context的内容
- contextTypes // 定义接收的 context的属性
import PropTypes from 'prop-types';
// 中间元素
const Message = ({text}) => (
<div>{this.props.text} <Button>Delete</Button></div>
)
// 需要共享 “color” 属性的孙子组件
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
Button.contextTypes = {
color: PropTypes.string
};
class MessageList extends React.Component {
// 定义要共享的 color 属性
getChildContext() {
return {color: "purple"};
}
render() {
return (<Message text={message.text} />)
}
}
// 定义要共享的 color 属性
MessageList.childContextTypes = {
color: PropTypes.string
};
demo:
React-Router v4, <Link/>
与 <Route/>
可以与 container Router
通信
????? FAQ ????? 通信是指啥?
<Link/>
,<Route/>
需要与<Router/>
有什么交互?
constructor(props, context)
// 构造函数componentWillReceiveProps(nextProps, nextContext)
// 接收propsshouldComponentUpdate(nextProps, nextState, nextContext)
// 是否应该updatecomponentWillUpdate(nextProps, nextState, nextContext)
// 组件将要 update 了
- 定义 contextType 就能使用context了
- context作为第二个参数传入到 constroctor 中
import PropTypes from 'prop-types';
const Button = ({children}, context) =>
<button style={{background: context.color}}>
{children}
</button>;
Button.contextTypes = {color: PropTypes.string};
getChildContext()
会自动更新, 在props 与 state 变更时调用.
getChildContext() {
return {type: this.state.type};
}
-
如果中间层的组件
shouldComponentUpdate
返回false, 底层组件不会被渲染 -
如何可靠地使用 context ? 资料 https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076