我在MobX中渲染一个基于嵌套商店(SquareModel
)的正方形。当点击方块时,我想在SquareModel
内开火,改变一个selected
属性,这反过来会调整方块的大小。但是,我似乎无法让广场对房产变化做出反应。关于如何使这个工作的任何想法?
沙箱:https://codesandbox.io/s/m51oyzz069
MainStore:
import { observable, decorate } from "mobx";
import SquareModel from "./SquareModel";
class MobXStore {
square = new SquareModel();
}
decorate(MobXStore, {
square: observable
});
export default new MobXStore();
NestedStore:
import { observable, action, decorate } from "mobx";
class SquareModel {
selected = false;
toggleSelection() {
console.log("toggle selection");
this.selected = !this.selected;
}
}
decorate(SquareModel, {
selected: observable,
toggleSelection: action
});
export default SquareModel;
阵营:
const App = observer(() => {
return (
<svg className="App">
<svg x={100} y={100}>
<Square
unit={MobXStore.square.selected ? 2 : 1}
onPointerUp={MobXStore.square.toggleSelection}
/>
</svg>
</svg>
);
});
export const Square = observer(({ unit, ...props }) => {
console.log("render square");
return (
<g {...props}>
<rect height={unit * 50} width={unit * 50} style={{ fill: "blue" }} />
</g>
);
});
toggleSelection方法中存在“this”错误
它应该看起来像:
onPointerUp = {() => MobXStore.square.toggleSelection()}
或者你需要在这里使用箭头功能:
toggleSelection = () => {