跨级组件通信

2020-06-11  本文已影响0人  tenro
当组件经过层层嵌套后,想要传值再用'props'就显得有点'2'了,
比较聪明的人往往会使用比较优雅的 'context'!   
既然描述的是 '比较聪明的人' 而不是 '非常聪明的人' 就注定'context是有局限性的'!
context本身是全局性的,全局性有个通病就是我要知道他是哪里来的就很难,
就像我在某个函数里面命名了一个全局的变量,
N年后,你要找到他在哪里声明的就费劲了,从而就导致'应用混乱,维护性差'!!!
故建议使用context是最好是不可变的全局性的信息,如:用户的信息,界面的颜色或主题等

跨级组件通信示例:
//子(孙子)组件
class Button extends Component {
      render()  {
            return (
                  <button style={{ backgound: this.context.color }} >
                        { this.props.children }
                  </button>
            )
      }
}

//声明contextTypes用于访问MessageList中定义的context数据
Button.contextTypes = {
    color: PropTypes.string
 };

//中间组件
class Message extends Component {
      render()  {
            return (
                  <div>
                        <Button>Delete</Button>
                  </div>
            )
      }
}

//父组件
class MessageList extends Component {
      //定义context需要实现的方法
      getChildContext(){
            return {
                    color: 'orange'
            }
      }
      render()  {
            return  <Message />;
      }
}

//声明context类型
MessageList.childContextTypes = {
      color: PropTypes.string
};
ReactDOM.render(
      <MessageList />,
      document.getElementById('app')
);
上一篇 下一篇

猜你喜欢

热点阅读