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

Tim*_*Tim 3 javascript jsx reactjs template-literals

我想知道什么是与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>
    );
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Web*_*ian 5

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

<h1>Total count: {this.state.totalCount}</h1>
Run Code Online (Sandbox Code Playgroud)

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

<h1>{`Total count: ${this.state.totalCount}`}</h1>
Run Code Online (Sandbox Code Playgroud)

  • 你可能会做``<h1> {`总数:$ {totalCount}`} </ h1>`` (2认同)