【问题标题】:{} vs. ${} in and ` vs. ' (backtick vs quote) [duplicate]{} vs. ${} in 和 ` vs. '(反引号 vs 引号)[重复]
【发布时间】:2020-07-31 01:01:24
【问题描述】:

我是 JSX 和一般 javascript 的新手,我对 {} 根据其内部和周围的内容具有多种含义感到困惑。在React docs 的以下示例中,我对{}${} 之间的区别感到困惑。
在一个解释钩子的例子中,我们看到<button onClick={() => this.setState({ count: this.state.count + 1 })}>

这里,最里面的花括号表示带有一对key: value 的JS 对象是作为唯一参数传递给this.setState() 的对象。

后来,在componentDidUpdatecomponentDidMount 方法中我们看到document.title = `You clicked ${this.state.count} times/`;

在这个 sn-p 中,花括号不包围 key: value 对,所以我知道它不是 JSON 对象。它在 JSX 中的 {} 内,所以 this.state.count 应该只计算为一个数字,但这个表达式中 $ 的含义是什么?

提前致谢!

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

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

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

【问题讨论】:

    标签: javascript jsx


    【解决方案1】:

    `` 和 $ 组合是一种连接字符串的方法,它比使用 + 的旧方法更容易阅读。

    例如,假设您通过某些输入获得了用户的名字,您可能会输出一些字符串,例如 Hi There Mark! 其中 Mark 是用户名。 你可以这样做 "Hi There" + user.firstname + "!" 要么 `Hi There ${user.firstname}!`.

    【讨论】:

      【解决方案2】:

      JavaScript 中,反引号之间的内容是 template string${...} 是可用于在模板中嵌入 JavaScript 表达式的语法。

      JSX 中,{...} 用于将动态值(与静态值相反)分配给组件上的 prop。

      【讨论】:

        猜你喜欢
        • 2011-01-23
        • 2013-07-12
        • 2011-02-15
        • 2014-09-28
        • 2015-12-20
        • 1970-01-01
        • 2016-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多