包装符号`{}`围绕反应渲染

时间:2018-05-21 02:51:25

标签: reactjs ecmascript-6

class App extends React.Component {
  renderSomething = () => `something`
  render() {
    return <div>{` `{` ${this.renderSomething()} `}` `}</div>
  }
}

https://codesandbox.io/s/6yomj6wj73

我想在屏幕上输出{something}而不修改renderSomething函数,任何线索为什么上面的代码都失败了?

1 个答案:

答案 0 :(得分:0)

创建一个模板字符串,用大括号括起你的内容,然后在JSX中使用那个。我将这些步骤分成多个变量,希望能让事情变得更加清晰。

class App extends React.Component {
  renderSomething = () => `something`

  render() {
    const innerText = this.renderSomething()
    const wrappedWithBraces = `{${innerText}}`
    return <div>{ wrappedWithBraces }</div>

    // in short: <div>{ `{${this.renderSomething()}}` }</div>
    // but I prefer the non-short version, since it's much more readable :)
  }
}