Domanda

Sto portando il seguente codice da AngularJS per reagire:

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

Ho provato:

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

non è riuscito con Parse Error: Line X: Unexpected token }.

il meglio che ho trovato è:

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

Questo è un sacco di " + this.state.XXX + " ed è molto difficile da leggere.

C'è un modo migliore per farlo?

È stato utile?

Soluzione

Ho trovato la funzione di micro-modelli in stile angolarjs.Esempio di utilizzo:

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

L'implementazione:

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

Non è una soluzione molto buona generale ma, penso, è meglio di " + this.state.XXX + ".

Altri suggerimenti

Che ne dici di:

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

quindi

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top