如何用字符串中的表达式插入 JSX?

希望实现以下目标:

<div className="total total-{obj.state}">

很明显,这样的结果是:

<div class="total total-{obj.state}">

在 JSX 中有没有一种优雅的方法来计算字符串中 {}中的表达式?

102901 次浏览

Try this (ES5):

<div className={'total total-' + obj.state}>...</div>

Or with ES6+

<div className={`total total-${obj.state}`}>...</div>

Remember that everything between { and } is just Javascript, so the expression is 'total total-' + obj.state which is then set as the class of the DOM node.

You could use a react expression and then the javascript es6 string interpolation

Something like this:

<div someProp={`${SomeConstOrVariableOrExpression} simple text`}></div>