Skip to content

Latest commit

 

History

History
132 lines (87 loc) · 3.08 KB

2018.2.26(context).md

File metadata and controls

132 lines (87 loc) · 3.08 KB

react context

context 与 HOC

资源: https://medium.com/dailyjs/reacts-%EF%B8%8F-new-context-api-70c9fe01596b

为什么我们要使用 context

尽管官方文档不建议使用 context, 但是 react-redux 等库都在使用 context 属性

context 基本用法

官方文档

资源:https://reactjs.org/docs/context.html

Context 的基础demo

  • 分享 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
};

作用

parent - children 之间相互通信

demo:

React-Router v4, <Link/><Route/> 可以与 container Router 通信

????? FAQ ????? 通信是指啥?<Link/>,<Route/> 需要与 <Router/> 有什么交互?

生命周期里的 context

无状态组件使用 context

  • 定义 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};

context 更新

tip1: 不要直接修改context

getChildContext() 会自动更新, 在props 与 state 变更时调用.

getChildContext() {
  return {type: this.state.type};
}

tip2: context 渲染并不可靠