在 Ember 中动态更改 CSS Class

Dynamically Change CSS Class in Ember

超级,Ember 的超级新手,如果这很简单,我们深表歉意。我想知道在组件内呈现的 CSS class 中动态更改属性的最佳方法。

我做了一个组件,像这样:

//route_template.hbs
{{map-view point=model}}

然后我通过point,它有两个坐标属性:model.xCoordinatemodel.yCoordinate

这是我的组件模板。你可以看到我目前正在使用这个 hacky 内联样式来设置页面上点位置的样式:

//component_template.hbs
{{#each point as |mapPoint|}}
   <i class="point-icon" style={{html-safe (concat 'left:' mapPoint.xCoordinate 'px; top:' mapPoint.yCoordinate 'px;')}}></i>
{{/each}}

我知道:恶心。有一个更好的方法吗?我应该做一个车把助手吗?一种行为?如果有人能指出我的大致方向,我可以从那里开始。非常感谢!

您不需要在 <> 类型元素中使用 concat 助手。你可以这样做

<i class="point-icon" style="left: {{mapPoint.xCoordinate}}px; top: {{mapPoint.yCoordinate}}px;"></i>

对于 {{}} 个块,尽管您需要使用 concat

{{my-component style=(concat 'left: ' mapPoint.xCoordinate 'px; top: ' mapPoint.yCoordinate 'px;')}}

此外,如果我是正确的,如果您的字符串中有标记,您只需要 html 安全。

https://guides.emberjs.com/v3.1.0/templates/writing-helpers/#toc_escaping-html-content

看看我的回答

可能 ember-css-properties 就是您要找的。另一种选择是助手或计算的 属性.

帮助者可以提供这个API:

<i class="point-icon" style={{build-css
  left=(concat mapPoint.xCoordinate 'px')
  top=(concat mapPoint.yCoordinate 'px')
}}></i>

甚至假设默认为 px

<i class="point-icon" style={{build-css
  left=concat mapPoint.xCoordinate
  top=concat mapPoint.yCoordinate
}}></i>

如果你想使用计算 属性 你会在你的模板中这样做:

<i class="point-icon" style={{myComputedStyle}}></i>

这是你的风格

myComputedStyle: computed('mapPoint.{xCoordinate,yCoordinate}', {
  get() {
    return htmlSafe(`
      left: ${xCoordinate}px;
      top: ${yCoordinate}px;
    `);
  }
}),

注意:对于所有这些(ember-css-properties 除外),您需要了解其含义:

如果用户可以将 mapPoint.xCoordinatemapPoint.yCoordinate 操作为意外值,您可能会打开一个安全漏洞!