加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react+mobx 编写withMessage 高阶组建

发布时间:2020-12-15 20:39:26 所属栏目:百科 来源:网络整理
导读:监听store中的amsg属性的变化来调用 提示框 withMessage // withComponents/withMessage.jsimport React,{ Component } from "react";import LightTip from "../components/lightTip";import { set } from "mobx";export default function withMessage(store

监听store中的amsg属性的变化来调用 提示框

withMessage

// withComponents/withMessage.js

import React,{ Component } from "react";
import LightTip from "../components/lightTip";
import { set } from "mobx";

export default function withMessage(storeName,key = "amsg") {
  if (!storeName) return console.error(`必须输入一个查询数据的store`);
  return function(Target) {
    return class WithMessage extends Component {
      componentWillMount() {
        let msg = this.props[storeName][key];
        if (msg === undefined) {
          set(this.props[storeName],{
            [key]: "",});
        }
      }
      close = () => {
        set(this.props[storeName],{
          [key]: "",});
      };
      render() {
        return (
          <>
            <LightTip msg={this.props[storeName][key]} onClose={this.close} />
            <Target {...this.props} />
          </>
        );
      }
    };
  };
}

使用

import React,{ Component } from "react";
import { observer,inject } from "mobx-react";
import withMessage from "../withComponents/withMessage";

const INDEXSTORE = "indexStore";

@inject(INDEXSTORE)
@observer
@withMessage(INDEXSTORE)
class Test extends Component {
  render() {
    const { indexStore } = this.props;
    return (
      <button
        onClick={() => {
          indexStore.amsg = "error";
        }}
      >
        click me
      </button>
    );
  }
}

export default Test;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读