模板文字作为JSX中的字符串内容

问题描述 投票:2回答:1

我想知道什么是与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>
    );
}

最佳做法或用例以不同方式使用它们是什么?

谢谢!

javascript reactjs jsx template-literals
1个回答
5
投票

目前React JSX不支持模板文字。正确的方法是这样的:

<h1>Total count: {this.state.totalCount}</h1>

编辑:您的第三种方式也是正确的,但我个人不会因为调试问题而推荐它​​,因为代码扩展时您需要扫描括号

<h1>{`Total count: ${this.state.totalCount}`}</h1>
© www.soinside.com 2019 - 2024. All rights reserved.