在props.children中逃脱卷曲括号

osx*_*sxi 16 javascript reactjs react-jsx

我正在尝试传递一个Handlebars模板,以便this.props.children使用以下JSX代码段进行处理:

<MyComponent>
  My address is {{address}}.
</MyComponent>
Run Code Online (Sandbox Code Playgroud)

结果是Uncaught ReferenceError: address is not defined.

解决方法是使用类似的东西:

<MyComponent>
  <span content="My address is {{address}}."></span>
</MyComponent>
Run Code Online (Sandbox Code Playgroud)

然后使用this.props.children.props.content.这是我发现基本上逃避{{address}}被JSX解释为插值的唯一方法.

有没有一种简单的方法来逃避JSX中的花括号?

jus*_*ris 17

尝试将组件内容包装成花括号:

<MyComponent>
  {"My address is {{address}}."}
</MyComponent>
Run Code Online (Sandbox Code Playgroud)

大括号中的所有内容都是表达式,不会被解析为JSX.至少,它适用于Babel REPL


Har*_*dha 5

由于模板文字在ES6中引入,我们可以在这里使用它们而不会引入太多花括号.

render() {
     let address = 'Somewhere on this earth!';
     return (
        <MyComponent>
            {`My address is ${address}`}
        </MyComponent>    
     );
}
Run Code Online (Sandbox Code Playgroud)

链接到JSFiddle

希望这可以帮助 :)