'&&'运算符用{this.props.children && React.cloneElement(this.props.children,{foo:this.foo})表示什么

Ara*_*gam 7 reactjs react-router react-native

我有使用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>
        )
      }
    }
Run Code Online (Sandbox Code Playgroud)

我想了解为什么我们在这里使用'&&'运算符.

sad*_*diq 19

这是短路评估

(if this part is true) && (this part will execute)
Run Code Online (Sandbox Code Playgroud)

它的简写:

if(condition){
   (this part will execute)
}
Run Code Online (Sandbox Code Playgroud)

  • 看起来它省去了对三元数执行 :null 的操作 (3认同)

Jef*_*oud 6

当&&和||时 以这种方式使用,它们被昵称为"短路运营商".在这种用法中,它可以被认为是"如果(某事是真的)"的快速.因此,如果this.props.children不为null,它将调用React.cloneElement.如果为null,则不会调用React.cloneElement.

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


Ale*_*ung 6

&&与您在任何javascript表达式中都可以找到的运算符完全相同,例如...

if( condition1 && condition2) {

}
Run Code Online (Sandbox Code Playgroud)

javascript的一个功能是表单的表达式...

(condition1 && condition2)
Run Code Online (Sandbox Code Playgroud)

如果condition1为true,则将求值为condition2;如果condition1为false,则将为null。它实际上是...的简写

if(condition1) {
    condition2;
}
Run Code Online (Sandbox Code Playgroud)

我们通过将React元素作为条件2使用此简写,得到...

(condition1 && <ReactElement />)
Run Code Online (Sandbox Code Playgroud)

这实际上是...

if(condition1) {
    <ReactElement />
}
Run Code Online (Sandbox Code Playgroud)

  • 那么“condition2”实际上并不是一个条件,因为它只依赖于“condition1”? (2认同)

Con*_*nan 0

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