【问题标题】:React ${} string replacer doesn't work [duplicate]React ${} 字符串替换器不起作用[重复]
【发布时间】:2018-01-31 14:22:32
【问题描述】:

我正在使用教科书学习 React,并且此特定示例中的字符串替换器 ${} 不起作用,无法弄清楚原因。我已经仔细检查了任何错别字以确保。到目前为止,本书中的其他示例运行良好。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      class Hello extends React.Component {
        constructor (props) {
          super(props)
          this.clickHandler = this.clickHandler.bind(this) //isolates 'this' of Hello class from other 'this'
        }
        clickHandler (e) {
          const name = this.props.name
          window.alert('Hello, ${name}') //!!this doesn't work....
        }
        render () {
          return (
            <div onClick={this.clickHandler}>Say Hello</div>
          )
        }
      }
      ReactDOM.render((<Hello name="Johnny" />),document.getElementById("root"))
    </script>
  </body>
</html>

【问题讨论】:

  • 用`(打勾)替换'。
  • 不要使用这个 '' 在选项卡上方和 esc 下方使用刻度即键。所以使用Hello, ${name}
  • 你应该使用反引号
  • 感谢大家的及时回复。以及模组和管理员的绝佳借口。我总是在发布之前仔细检查,但无论是来自谷歌还是堆栈溢出,${} 都没有产生任何搜索结果。所以无论如何我不得不发布这个问题。

标签: javascript html reactjs


【解决方案1】:

使用反引号

window.alert(`Hello, ${name}`)

【讨论】:

  • 为什么会这样是${}不是React提供的,是ES6。可以插入内容的模板文字。
  • 谢谢。我不知道这被称为“模板文字”。这本书没有提供任何关于它的细节,因为它主要是一本 React 书,而不是 ES6 书。
  • @SungryeolPark 很乐意为您提供帮助:)
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 2017-07-25
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 2018-08-26
  • 2013-09-14
相关资源
最近更新 更多