Reagir.js:Passando valores dentro de atributos
-
21-12-2019 - |
Pergunta
Estou portando o seguinte código do AngularJS para o React:
<div style="translate: translate({x}px, {y}px) scale({scale}) rotate({angle}deg)"}></div>
Tentei:
<div style="translate: translate({this.state.x}px, {this.state.y}px) scale({this.state.scale}) rotate({this.state.angle}deg)"}></div>
Falhou com Parse Error: Line X: Unexpected token }
.
O melhor que descobri foi:
<div style={{transform: "translate(" + this.state.x + "px, " + this.state.y + "px) \
scale(" + this.state.scale + ") \
rotate(" + this.state.angle + "deg)"}}></div>
Isso é muito " + this.state.XXX + "
e é muito difícil de ler.
Existe uma maneira melhor de fazer isso?
Solução
Eu criei uma função de micromodelos no estilo AngularJS.Exemplo de uso:
<div style={this.evalTpl("translate: translate({{x}}px, {{y}}px) scale({{scale}}) rotate({{angle}}deg)")}></div>
A implementação:
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 geral, não é uma solução muito boa, mas acho que é melhor do que " + this.state.XXX + "
.
Outras dicas
Que 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
;
});
};
Então
<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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow