为了进一步实现整洁架构,使用 mvp 的方式组织你的前端代码,让项目更加清晰
-
ViewState,一般是要在界面上显示需要的数据,或者临时数据
-
View,一般是 react,vue 之类的视图层,它显示数据,并将事件绑定到 Presenter
-
Presenter, 提供方法和 ViewState 给到 View
-
service 实现业务逻辑, 为Presenter提供服务
npm install @clean-js/presenter @clean-js/react-presenter --save
or
yarn add @clean-js/presenter @clean-js/react-presenter
import { Presenter, injectable } from '@clean-js/presenter';
interface IViewState {
loading: boolean;
name: string;
}
@injectable()
export class NamePresenter extends Presenter<IViewState> {
constructor() {
super();
this.state = {
loading: false,
name: 'lujs',
};
}
changeName() {
this.setState((s) => {
s.name += '!';
});
}
}
import React from 'react';
import { usePresenter } from '@clean-js/react-presenter';
import { NamePresenter } from './presenter';
const Name = () => {
const { presenter, state } = usePresenter(NamePresenter);
return (
<div>
<p>name: {state.name}</p>
<button
onClick={() => {
presenter.changeName();
}}
>
hi
</button>
</div>
);
};
export default Name;
设置 tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
需要在.umirc中添加插件“babel-plugin-transform-typescript-metadata”
import { defineConfig } from 'umi';
export default defineConfig({
npmClient: 'pnpm',
extraBabelPlugins: ['babel-plugin-transform-typescript-metadata'],
});