'&&'操作符用{this.props.children &&React.cloneElement (t

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

本文关键字:React cloneElement children this 操作符 props      更新时间:2023-09-26

我有一个使用react router渲染的react类。我理解React。cloneElement用于将元素从父元素传递给子元素。但是为什么'&&'操作符对这种语句有什么作用呢?

class Users extends React.Component {
    getInitialState() {
      return {
          page:0
        }
     },      
    foo(){
        this.setState({'page':1})
     }
      render() {
        return (
          <div>
            <h2>Users</h2>
            { this.props.children && React.cloneElement(this.props.children, {
    foo:this.foo})
          </div>
        )
      }
    }

我想知道为什么我们在这里使用'&&'运算符

短路评估

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

的简写
if(condition){
   (this part will execute)
}

<span;与任何javascript表达式(如…>

)中的操作符完全相同。
if( condition1 && condition2) {
}

javascript的一个特性是…

(condition1 && condition2)
如果condition1为真,

将求值为condition2,如果condition1为假,则求值为null。它是…的有效缩写

if(condition1) {
    condition2;
}

我们通过放置一个React元素作为条件2来使用这种简写,得到…

(condition1 && <ReactElement />)

这实际上是…

if(condition1) {
    <ReactElement />
}

当&而||就是这样使用的,他们被戏称为"短路操作员"。在这种用法中,它可以被认为是一个快速的"如果(某事是真的)"。如果this。props。children不为空,它会调用react。cloneelement。如果它是空的,它将不会调用React.cloneElement。

这里是官方React文档的链接,进一步阅读:https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-with-logical-ampamp-operator

简单来说,&&的目的是:

当没有子元素时,不要尝试克隆和渲染子元素孩子。

如果你像这样使用Users

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

然后Child1Child2将被渲染额外的道具foo

但是如果以这种方式使用父组件<Users/><Users></Users>,则没有子组件可以渲染。所以我们在调用React.cloneElement之前执行一个检查。

&&等价于布尔值AND: 1 AND A === A => 1 && A = A

||等价于布尔值OR: 1 OR A = 1 => 1 || A = 1

您可以删除第一个子句并只使用React.cloneElement(this.props.children, {foo:this.foo}),但它包含在您的示例中是为了说明没有要呈现的子组件的情况。