我想知道什么是与JSX标签内的变量混合的字符串值的最佳实践,我列出了我熟悉的选项:
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>
);
}
最佳做法或用例以不同方式使用它们是什么?
谢谢!
目前React JSX不支持模板文字。正确的方法是这样的:
<h1>Total count: {this.state.totalCount}</h1>
编辑:您的第三种方式也是正确的,但我个人不会因为调试问题而推荐它,因为代码扩展时您需要扫描括号
<h1>{`Total count: ${this.state.totalCount}`}</h1>