如何从一系列颜色中动态更改聚合物 1.0 纸按钮颜色?

How to change polymer 1.0 paper-button color dynamically from an array of colors?

我有一个数组 buttonColors,它有一组十六进制格式的颜色。 现在我想显示一组纸质按钮,每个按钮的颜色都存在于 buttonColors 数组中。如何在 Polymer 1.0 中实现?

<template is="dom-repeat" items="{{buttonColors}}">
      <paper-button style="background-color:{{item}}" >
                  <b>click me</b>
      </paper-button>
</template>

上面的代码片段似乎不起作用。请帮忙。

您需要创建一个函数并按以下方式调用它

<template is="dom-repeat" items="{{buttonColors}}">
      <paper-button style="{{computeStyle(item)}}" >
                  <b>click me</b>
      </paper-button>
</template>

<script>
computedStyle:function(cl)
{
 var s= "background-color:"+cl;
  return s;
}
</script>

ebidel 的评论一如既往的出色。 (他是 Google 负责构建 Polymer BTW 的天才之一)

1.0 doesn't support expressions in {{}} bindings. You'll need to make it a computed property: style="{{_computeStyle(item)}}" ... Documentation

下面,我编写了一些示例代码供您参考。


示例代码

<dom-module id="x-element">
  <template is="dom-repeat" items="{{buttonColors}}">
    <paper-button style$="{{_computeStyle}}"> <b>click me</b> </paper-button>
  </template> ...
  <script>
    (function() {
      Polymer({
        is: "x-element",
        properties: {
          value: {
            type: Number,
            notify: true
          }
        },
        _computeStyle: function(item) {
          // Compute style here
          return "background-color:red";
        }
      });
    })()
  </script>
</dom-module>