Template literals as string content in JSX

百般思念 提交于 2020-08-19 12:08:28

问题


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?

Thanks!


回答1:


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>

Edit: 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>


来源:https://stackoverflow.com/questions/52169161/template-literals-as-string-content-in-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!