reactjs - 我如何在 Typescript 文件中导入 Mobx 状态树并引用其值,而不使用组件?
我想在一个纯 TypeScript 文档中使用 MST 中的值。它没有组件,只是一个 CSS 值的对象,这些值在其他组件的元素的样式标签中被引用。这可能吗?如果可以,我该如何操作?
编辑:这里有一些代码
Mobx 状态树
import { types } from 'mobx-state-tree'
export const BotCSS = types.model({
chatBackground: types.optional(types.string, '#fff'),
fontType: types.optional(types.string, 'Open Sans'),
hoverFillColor: types.optional(types.string, '#306aca'),
hoverFontColor: types.optional(types.string, '#f2f2f2'),
primaryColor: types.optional(types.string, '#427ee1'),
secondaryColor: types.optional(types.string, '#f2f2f2'),
typingAnimationDots: types.optional(types.string, '#427ee1'),
typingAnimationFill: types.optional(types.string, '#f2f2f2'),
userResponseColor: types.optional(types.string, '#427ee1')
})
export type IBotCSS = typeof BotCSS.Type
theme.ts 文档包含 theme 对象 - 我想将 mobx 的值设置为其中一些变量
const userMessageBackgroud = `${blue}`
const userMessageBorder = `${blue}`
const userMessageColor = `${white}`
const minimizeboxBackgroud = `${blue}`
const minimizeboxColor = `${white}`
export const theme = {
AgentBar: {
Avatar: {
size: '42px'
},
css: {
backgroundColor: `${secondaryColor}`,
borderColor: `${avatarBorderColor}`
}
},
AvatarImg: {
backgroundColor: 'transparent',
border: 'none',
borderRadius: 0,
height: '38px',
width: '40px'
}, (...etc)
所以基本上,在这个 theme.ts 文档的顶部有一些变量,这些变量在 theme 对象中使用。我想在 mobx 中设置的值等于文档顶部的变量声明
答案#1
首先,你应该意识到 MobX 和 MST 是完全独立的状态管理库,可以完全独立工作,无需任何组件框架。
其次,你不能直接在 MST 中将值设置到 store 的属性上(顺便说一句,首先需要创建 store 的实例,例如:const botCss=BotCSS.create())。你需要为此定义专门的 setter(或者按照 MobX 的术语叫做 action)。大概像这样:
import { types } from 'mobx-state-tree'
export const BotCSS = types.model({
chatBackground: types.optional(types.string, '#fff'),
fontType: types.optional(types.string, 'Open Sans'),
hoverFillColor: types.optional(types.string, '#306aca'),
hoverFontColor: types.optional(types.string, '#f2f2f2'),
primaryColor: types.optional(types.string, '#427ee1'),
secondaryColor: types.optional(types.string, '#f2f2f2'),
typingAnimationDots: types.optional(types.string, '#427ee1'),
typingAnimationFill: types.optional(types.string, '#f2f2f2'),
userResponseColor: types.optional(types.string, '#427ee1')
})
.actions(self => {
setCss(data) {
Object.assign(self, data);
}
})
export const botCss = BotCSS.create() // you might even export the instance itself
export type IBotCSS = typeof BotCSS.Type
然后在另一个模块中,你可以导入该实例或类型(然后创建一个实例)并使用新的值调用 setter:
import { botCss } from './BotCSS'
botCss.setCss({
chatBackground: '#ff0000'
});
答案#2
所以你忘记创建一个存储,并且为了更改存储中字段的状态,你需要创建方法(“动作”)。
这是一个示例
