如何在没有组件的情况下导入 Mobx 状态树并在 Typescript 文件中引用它的值?

How do I import a Mobx state tree and reference its values in a Typescript file without a component?

我想在 vanilla 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 带有主题 obj 的文档 - 我想将 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 文档的顶部有许多变量用于主题对象。我想将 mobx 中的值设置为等于文档顶部的变量声明

所以您忘记创建商店,要更改商店中字段的状态,您需要创建方法("actions")。

这是一个sample

首先你应该意识到 MobX 和 MST 是完全独立的状态管理库,它们可以完美地独立工作,不需要任何组件框架。

其次,您不能直接在 MST 中将值设置为商店的属性(首先创建一个商店实例,例如:const botCss = BotCSS.create())。您需要为此定义专用的 setter(或 MobX 术语中的 actions)。类似于:

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'
});