admin管理员组

文章数量:1295130

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!

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!

Share Improve this question asked Sep 4, 2018 at 15:01 TimTim 1673 silver badges9 bronze badges 1
  • I don't think #2 works. You could inline #3, but it would be very unappealing, especially pared to #1. – Bergi Commented Sep 4, 2018 at 15:09
Add a ment  | 

1 Answer 1

Reset to default 9

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 remend it because of debug issues as you would need to scan for brackets as the code expands

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

本文标签: javascriptTemplate literals as string content in JSXStack Overflow