Mbox
Mbox是状态管理器的一种,他主要局域Es6修饰符 @,修饰符现在还处于提案阶段
当我们需要在多个组件之间共享属性,复用扩展一些方法,写法不优雅decorator就是解决这个问题
@作为修饰符,即可作用与class,页可以作用 属性
准备
脚手架兼容修饰器
npm install react-app-rewired customize-cra --save-dev /* package.json */ "scripts": {
- "start": "react-scripts start", + "start": "react-app-rewired start", - "build": "react-scripts build", + "build": "react-app-rewired build", - "test": "react-scripts test --env=jsdom", + "test": "react-app-rewired test --env=jsdom", } //然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。 const {
override, addDecoratorsLegacy } = require('customize-cra'); module.exports = override( addDecoratorsLegacy() );
讯享网
作用
讯享网 function testDec(target,name,desscriptor){
target.uname="Msea"; target.upwd=""; // console.log(name)//修改器后面的 方法名 var run =desscriptor.value; desscriptor.value=function(){
run(); console.log("喵喵~~~"); }; } @testDec class One{
} @testDec class Two{
} //属性共享 // console.log(new One()) // console.log(new Two()) //扩展方法 // class TestOne {
// @testDec test(){
// console.log("小猫") // } // } var testOneFn= new TestOne(); testOneFn.test();
安装
cnpm i mobx@5.15.0 mobx-react@6.1.4 --save-dev
初始化reducer
讯享网import {
observable,action,computed} from "mobx"; export default class {
//属性变量 @observable name="苹果"; @observable price=18; @observable num=0; // 操作方法 @action.bound add(){
//.bound 修改 事件上下文 执行当前 reducer this.num++; console.log(this); } //属性计算 @computed get countPrice(){
return this.num*this.price; } }
初始化 store
import indexReducer from "../components/index/indexReducer" import listReducer from "../components/list/listReducer" class RootStore {
constructor(){
this.indexReducer=new indexReducer(); this.listReducer=new listReducer(); } } export default new RootStore();
注入全局 mbox-react
讯享网import React from "react"; import ReactDOM from "react-dom"; import App from "./App.jsx"; import {
Provider } from "mobx-react"; import rootStore from "./store"; ReactDOM.render( <Provider {
...rootStore}> <App /> </Provider>, document.getElementById("root") );
组件使用
import React from 'react'; import {
inject,observer} from "mobx-react"; @inject("indexReducer","listReducer") //注入 reducer @observer //监听数据变化 class Index extends React.Component{
render(){
console.log(this.props); let {
name,price,num,add,countPrice}=this.props.indexReducer; let {
uname}=this.props.listReducer; return ( <div> <h1>Index</h1> <div> 种类:{
name} </div> <div> 价格:{
price} </div> <div> 数量:{
num} </div> <div> 总价:{
countPrice} </div> <button onClick={
add.bind(this)}>add</button> {
uname} </div> ) } } export default Index;

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/135541.html