我正在查看具有渲染语句的回购,其条件是将实际组件作为逻辑条件。
return <Component> { this.state.loading == true && <ActivityIndicator animating={this.state.loading} /> || <View> ... </View> } </Component>我将它解释为'如果状态正在加载',并且这个对reactDOM.render()的调用返回一些东西,或者这个调用对reacDOM.render()返回一些东西,那么......
但THEN正在让我。 那又怎么样?
这是一种三元? Component内部的花括号是什么? 条件的结果在哪里指定?
I am looking at a repo that has a render statement with a conditional that has actual components as logical conditions.
return <Component> { this.state.loading == true && <ActivityIndicator animating={this.state.loading} /> || <View> ... </View> } </Component>I am interpreting it as, 'if state is loading' AND this call to reactDOM.render() returns something OR this call to reacDOM.render() returns something, then...
but the THEN is getting me. Then what?
Is this some sort of ternary? What are the curly brackets inside of Component? Where is the result of the condition specified?
最满意答案
这就是所谓的短路评估 。
这是javascript的语言功能。 用&&和||链接表达式时 它将始终是最后返回的值,即被评估。 Python对and和操作符也是一样的。 像PHP这样的其他语言总是返回一个布尔值。
其实这意味着:
expr1 && expr2
如果它可以转换为false,则返回expr1 ; 否则,返回expr2 。 因此,当与布尔值一起使用时,如果两个操作数都为真,则&&返回真; 否则,返回false。
expr1 || expr2
如果可以将其转换为true,则返回expr1 ; 否则,返回expr2 。 因此,当与布尔值一起使用时,|| 如果任一操作数为真,则返回true。
此外, &&优先于|| 这意味着a || b && c a || b && c相当于a || (b && c) a || (b && c) 。
你的例子只是将其中两个链接在一起导致:“如果this.state.loading是真的返回<ActivityIndicator>否则返回<View> ”。 这滥用了这样一个事实,即null , undefined , true和false是有效的节点,它们实际上并没有为条件呈现渲染任何内容。
This is called Short-circuit evaluation.
It's a language feature of javascript. When chaining expressions with && and || it will be always the last value returned, that is evaluated. Python does the same with and and or operators. Some other languages like e.g. PHP always return a boolean value.
In fact that means:
expr1 && expr2
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.
Furthermore the && has precedence over || which means that a || b && c is equivalent to a || (b && c).
Your example just chains two of these together leading to: "If this.state.loading is truthy return <ActivityIndicator> else return <View>". This abuses the fact, that null, undefined, true and false are valid nodes that do not actually render anything for conditional rendering.
更多推荐
发布评论