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

问题描述 投票:1回答:2

我想在vanilla打样文档中使用MST中的值。它没有组件,只是css值的对象,在其他组件的元素的样式标记中引用。这可能吗?如果是这样,我该怎么做呢?

编辑:这是一些代码

Mobx State Tree

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

带有主题obj的theme.ts文档 - 我想将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中的值设置为等于文档顶部的变量声明

reactjs typescript mobx mobx-state-tree
2个回答
0
投票

因此,您忘记创建商店并更改商店中字段的状态,您需要创建方法(“操作”)。

这是一个sample


0
投票

首先,您应该意识到MobX和MST是完全独立的状态管理库,并且可以完全独立地工作,而无需任何组件框架。

其次,您不能直接在MST中将值设置为商店中的属性(首先创建商店btw的实例,例如: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

然后在另一个模块中,您可以导入实例或Type(然后创建一个实例)并使用新值调用setter:

import { botCss } from './BotCSS'

botCss.setCss({
   chatBackground: '#ff0000'
});
© www.soinside.com 2019 - 2024. All rights reserved.