Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - Cannot render boolean value in JSX?

I am trying to render boolean value inside JSX, however React is evaluating it as expression and isn't returning anything after the component is returned.

Any workaround for this?

Here is an example

var ipsumText = true;

ReactDOM.render(
  <div>
     Boolean Value:    {ipsumText}
  </div>,
  document.getElementById('impl')
);

Just shows compiled HTML as

<div data-reactid=".0"><span data-reactid=".0.0">Boolean Value:    </span></div>

EDIT: Here is the JSBin link for the example http://jsbin.com/nibihodoce/1/edit?html,js,output

EDIT 2: I have already explored the .toString() alternative, however since I am iterating over an array of objects and a particular field of that object can have string/integer/boolean kind of value. Applying .toString() to all of 'em doesn't seem optimal.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Boolean Value: { ipsumText.toString() }

or

Boolean Value: { String(ipsumText) }

or

Boolean Value: { '' + ipsumText }

or

{`Boolean Value: ${ipsumText}`}

or

Boolean Value: { JSON.stringify(ipsumText) }

I prefer the second option. Universal, fast, works for all primitive types: Boolean( smth ), Number( smth ).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...