Correct way to define an empty dom element in React

后端 未结 2 713
花落未央
花落未央 2021-02-05 00:19

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

var checkBox = this.props.checkbox ? 

        
相关标签:
2条回答
  • 2021-02-05 01:01

    Use false, null or undefined.

    This snippet shows the behaviour of rendering falsy values in React:

    <meta charset="UTF-8">
    <script src="https://fb.me/react-0.13.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.13.2.js"></script>
    <div id="app"></div>
    <script type="text/jsx;harmony=true">void function() { "use strict";
    
    var falsyValues = [false, 0, "" , null, undefined, NaN]
    
    var App = React.createClass({
      componentDidMount() {
        [].slice.call(React.findDOMNode(this).childNodes)
          .forEach(child => console.log(child.outerHTML))
      },
      render() {
        return <div>
          {falsyValues.map(falsy => <div id={'test-' + falsy}>
            Before
            {falsy}
            After
          </div>)}
        </div>
      }
    })
    
    React.render(<App/>, document.getElementById('app'))
    
    }()</script>

    false, null and undefined don't generate anything:

    <div id="test-false" data-reactid=".0.0"><span data-reactid=".0.0.0">Before</span><span data-reactid=".0.0.2">After</span></div>
    <div id="test-null" data-reactid=".0.3"><span data-reactid=".0.3.0">Before</span><span data-reactid=".0.3.2">After</span></div>
    <div id="test-undefined" data-reactid=".0.4"><span data-reactid=".0.4.0">Before</span><span data-reactid=".0.4.2">After</span></div>
    

    Whereas '', 0 and NaN do:

    <div id="test-0" data-reactid=".0.1"><span data-reactid=".0.1.0">Before</span><span data-reactid=".0.1.1">0</span><span data-reactid=".0.1.2">After</span></div>
    <div id="test-" data-reactid=".0.2"><span data-reactid=".0.2.0">Before</span><span data-reactid=".0.2.1"></span><span data-reactid=".0.2.2">After</span></div>
    <div id="test-NaN" data-reactid=".0.5"><span data-reactid=".0.5.0">Before</span><span data-reactid=".0.5.1">NaN</span><span data-reactid=".0.5.2">After</span></div>
    

    As a convenience. you can conditionally generate content inline if the value you're testing against will be false, null or undefined when the conditional content shouldn't be displayed:

    <div>
        ...
        {this.props.checkbox && <span className='checkbox'></span>}
        ...
    </div>
    
    0 讨论(0)
  • 2021-02-05 01:06

    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>
    
    0 讨论(0)
提交回复
热议问题