Pregunta

Estoy portando el siguiente código de angularjs para reaccionar:

<div style="translate: translate({x}px, {y}px) scale({scale}) rotate({angle}deg)"}></div>

Lo intenté:

<div style="translate: translate({this.state.x}px, {this.state.y}px) scale({this.state.scale}) rotate({this.state.angle}deg)"}></div>

Falló con Parse Error: Line X: Unexpected token }.

Lo mejor que acumulé es:

<div style={{transform: "translate(" + this.state.x + "px, " + this.state.y + "px) \
    scale(" + this.state.scale + ") \
    rotate(" + this.state.angle + "deg)"}}></div>

Eso es mucho de " + this.state.XXX + " y es muy difícil de leer.

¿Hay una mejor manera de hacerlo?

¿Fue útil?

Solución

Se me ocurrió con la función de micro-plantillas de estilo angularjs.Ejemplo de uso:

<div style={this.evalTpl("translate: translate({{x}}px, {{y}}px) scale({{scale}}) rotate({{angle}}deg)")}></div>

La implementación:

evalTpl: function(str) {
    var state = this.state;
    return str.replace(/{{.+?}}/g, function(name) {
        name = name.slice(2, -2).trim();
        var value = state[name];
        if (typeof value === 'undefined' || value === null || (!value && isNaN(value))) {
            throw new Error('this.state[' + JSON.stringify(name) + '] is ' + value);
        }
        return value;
    });
}

No es muy buena solución en general, pero creo, es mejor que " + this.state.XXX + ".

Otros consejos

¿Qué tal:

format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number] 
        : match
      ;
   });
};

luego

<div style={{transform: this.getTransform()}}></div>
[...]
getTransform: function() {
   var s = this.state;
   return format("translate({0}px, {1}px) scale({2}) rotate({3}deg)",
            s.x, s.y, s.scale, s.angle);
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top