模板文字作为JSX中的字符串内容 [英] Template literals as string content in JSX
本文介绍了模板文字作为JSX中的字符串内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道将字符串值与JSX标签内的变量混合在一起的最佳做法是什么,我列出了我熟悉的选项:
I'm wondering whats the best practice for strings values mixed with variables inside JSX tags, I've listed the options I'm familiar with:
render() {
const {totalCount} = this.state;
const totalCountStr = `Total count: ${totalCount}`;
return (
<div>
<h1>Total count: {totalCount}</h1> // 1
<h1>`Total count: ${totalCount}`</h1> // 2
<h1>{totalCountStr}</h1> // 3
</div>
);
}
什么是最佳实践或用例以不同的方式使用它们?
What's the best practice or the use cases to use them differently?
谢谢!
推荐答案
React JSX当前不支持模板文字.正确的方法是这样的:
Template literals aren't supported by React JSX currently. The correct way to do it is like so:
<h1>Total count: {this.state.totalCount}</h1>
您的第三种方法也是正确的,但是由于调试问题,我个人不推荐这样做,因为随着代码扩展,您需要扫描方括号
Your third way is also correct, but I personally wouldn't recommend it because of debug issues as you would need to scan for brackets as the code expands
<h1>{`Total count: ${this.state.totalCount}`}</h1>
这篇关于模板文字作为JSX中的字符串内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文