最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Escape Curly Brackets in props.children - Stack Overflow

programmeradmin0浏览0评论

I'm trying to pass a Handlebars template to be processed as this.props.children using the following JSX snippet:

<MyComponent>
  My address is {{address}}.
</MyComponent>

The result is Uncaught ReferenceError: address is not defined.

A workaround was to use something like:

<MyComponent>
  <span content="My address is {{address}}."></span>
</MyComponent>

And then use this.props.children.props.content. This is the only way I've found to essentially escape {{address}} being interpreted as interpolation by JSX.

Is there a straightforward way to escape curly braces in JSX?

I'm trying to pass a Handlebars template to be processed as this.props.children using the following JSX snippet:

<MyComponent>
  My address is {{address}}.
</MyComponent>

The result is Uncaught ReferenceError: address is not defined.

A workaround was to use something like:

<MyComponent>
  <span content="My address is {{address}}."></span>
</MyComponent>

And then use this.props.children.props.content. This is the only way I've found to essentially escape {{address}} being interpreted as interpolation by JSX.

Is there a straightforward way to escape curly braces in JSX?

Share Improve this question edited Jan 31, 2016 at 3:59 0m3r 12.5k15 gold badges40 silver badges75 bronze badges asked Sep 2, 2015 at 21:49 osxiosxi 2781 gold badge2 silver badges8 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 20

Try to wrap component content into curly braces:

<MyComponent>
  {"My address is {{address}}."}
</MyComponent>

All content in braces will be an expression and will not be parsed as JSX. At least, it works in Babel REPL

As Template Literals are introduced in ES6, we can use them here without introducing too many curly braces.

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

Link to JSFiddle

Hope this helps :)

Try this:

<MyComponent>
  {'My address is {{address}}.'}
</MyComponent>

Since I'm not allowed to comment yet ... ;) Of course you don't have to escape the whole text - just the curly brackets. What you do in your case is a matter of personal preference.

<MyComponent>
 My address is {"{{"}address{"}}"}.
</MyComponent>

I suggest that you use the new JavaScript string literals.

THIS:

{`{}`}

SHOULD PRINT:

{}

So, in your case make all of it a string

{`My address is {{address}}.`}

Should print:

My address is {{address}}.

Peace! ✌️

发布评论

评论列表(0)

  1. 暂无评论