What does '&&' operator indicate with { this.props.children && React.cloneElement(this.props.children, { foo:this.foo})

前端 未结 5 1913
悲哀的现实
悲哀的现实 2020-12-15 11:22

I have react class that is rendered using react router. I understand that React.cloneElement is used to pass elements from parent to child. But why/what does the \'&&

相关标签:
5条回答
  • 2020-12-15 11:50

    It's Short circuit evaluation

    (if this part is true) && (this part will execute)
    

    And it shorthand of:

    if(condition){
       (this part will execute)
    }
    
    0 讨论(0)
  • 2020-12-15 11:54

    The && is the exact same operator as you would find in any javascript expression, such as...

    if( condition1 && condition2) {
    
    }
    

    It is a feature of javascript that an expression of the form...

    (condition1 && condition2)
    

    will evaluate to condition2, if condition1 is true, or null if condition1 is false. It is effectively shorthand for...

    if(condition1) {
        condition2;
    }
    

    We use this shorthand by placing a React element as condition 2, getting...

    (condition1 && <ReactElement />)
    

    which is effectively...

    if(condition1) {
        <ReactElement />
    }
    
    0 讨论(0)
  • 2020-12-15 11:55

    In simple words the purpose of that && is:

    Do not attempt to clone and render children when there are no children.

    So if you use Users like this:

    <Users>
       <Child1 />
       <Child2 />
    </Users>
    

    then both Child1 and Child2 will get rendered with additional props foo.

    But if the parent is used in this way <Users/> or <Users></Users>, there are no child components to render. So we are performing a check before we invoke React.cloneElement.

    && is equivalent to boolean AND: 1 AND A === A => 1 && A = A

    || is equivalent to boolean OR: 1 OR A = 1 => 1 || A = 1

    0 讨论(0)
  • 2020-12-15 12:06

    You could drop that first clause and just use React.cloneElement(this.props.children, {foo:this.foo}), but it's included in your example to account for cases where there are no child components to be rendered.

    0 讨论(0)
  • 2020-12-15 12:09

    When && and || are used in this way, they are nicknamed "short circuit operators". In this usage, it can be thought of as a quickie "if (something is true)". So, if this.props.children is not null, it will call React.cloneElement. If it is null, it will not call React.cloneElement.

    Here is a link on the official React documentation, with further reading: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-with-logical-ampamp-operator

    0 讨论(0)
提交回复
热议问题