Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Correct way to define an empty dom element in React

I send an optional parameter checkbox inside a prop to a component:

var checkBox = this.props.checkbox ? <span className='checkbox'></span> : null;

Then I put it like this:

<div>
    ...
    {checkBox}
    ...
</div>

As seen from above, I assign null to the variable. But I can instead assign empty string '' which seems to give the same result.

What's the proper one?

question from:https://stackoverflow.com/questions/30097091/correct-way-to-define-an-empty-dom-element-in-react

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

1 Reply

0 votes
by (71.8m points)

You need to use null. If you use an empty string like '' then react will create an empty span dom element, so it's not the same.

var label1 = <label>My Label</label>; // react generates a label element
var label2 = null; // react doesn't generate any dom element
var label3 = ''; // react generates and empty span like <span></span>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...