为什么在 React 中你可以在不使用模板文字语法的情况下在 html 元素中表达变量?

why in React can you express a variable inside an html element without using the template literal sintax?

我正在关注和阅读一堆关于 React 的课程,但我很困惑,有时我看到使用模板文字符号来表达 html 元素内的变量,例如 ph 元素,有些时候对于相同的元素没有这样的用途。来自 ReactJS documentation 的示例:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

为什么p标签里面的表达式不是这样写的?

<p>`You clicked ${this.state.count} times`</p>

在 JSX 中,JavaScript 表达式 总是由 { } 括号分隔。例如

{this.state.count}
{() => this.setState({ count: this.state.count + 1 })}

除非你使用括号,否则你不能使用 JavaScript 表达式 - 你只能写纯文本。这就是语法的设计方式。

如果需要,您 可以 <p> 内容使用模板文字,但模板文字是 JS 表达式,因此您需要将整个内容括起来<p> 的:

<p>{`You clicked ${this.state.count} times`}</p>

模板文字语法仅在代码的 javaScript 区域内可用,因此您只能在 {}

内使用它

所以在你的情况下它会像这样完成。

<p>{`You clicked ${this.state.count} times`}</p>

但在这种情况下,如果没有像这样的模板文字,这样做真的更简单

<p>You clicked {this.state.count} times</p>

例如,如果您只是打印一个数字或字符串的值,则不需要模板字符串来显示变量。

您不需要模板字符串来显示数组或对象中的值

{obj.key}
{array[3])

上面的例子都将不带文字打印

如果出于某种原因您需要显示 true 或 false 字样,这同样不适用于布尔值。

我认为人们只是习惯了使用它们,所以在反应中继续这样做,但在大多数情况下没有任何必要