了解 JSX 中的条件语句
Understanding conditional statements in JSX
试图理解现有reactjs代码的一些语句
<Modal.Footer>
{ getButtons.call(this)}
{ this.props.footerLinkText && getFooterLink.call(this) }
</Modal.Footer>
如何评价?
this.props.footerLinkText && getFooterLink.call(this)
我明白这是一个条件?
还有这个代码:
function cancelBtn() {
return (
<Form.Btn type={ this.props.closeBtnType || 'secondary-outline' }
size={ this.props.closeBtnSize || 'lg' }
key="cancelBtn"
onClick={ this.props.closeBtnAction ? this.doCloseAction.bind(this) : this.close.bind(this) }
>{ this.props.closeBtnText || 'Cancel' }</Form.Btn>
);
}
不确定。只需要快速解释一下。
二元和三元运算符
您在第一个示例中看到的是使用逻辑 'AND' 运算符 &&
的二元短路求值表达式。 参见:Logical Operators - JavaScript | MDN
在第二个示例中,您有一系列使用逻辑 'OR' 运算符 ||
的二元短路求值表达式,然后是使用三元运算符 ?
的条件求值:
。 参见:Conditional (ternary) Operator - JavaScript | MDN
这些都不是 ReactJS 原生的,但它们非常适合在 JSX 中使用,因为它们是可以计算的表达式 "inline",而像 if
-else
这样的语句除非放置在 immediately-invoked function expression or moved out of the JSX markup. See: If-Else in JSX | React
中,否则不工作
另请参阅:
{ this.props.footerLinkText && getFooterLink.call(this) }
这是一个Short-Circuit Evaluation。意思是如果this.props.footerLinkText
为真,getFooterLink
就会被执行。
{ this.props.closeBtnText || 'Cancel' }
如果 this.props.closeBtnText
为真,则返回 Cancel
。结果会显示Cancel
试图理解现有reactjs代码的一些语句
<Modal.Footer>
{ getButtons.call(this)}
{ this.props.footerLinkText && getFooterLink.call(this) }
</Modal.Footer>
如何评价?
this.props.footerLinkText && getFooterLink.call(this)
我明白这是一个条件?
还有这个代码:
function cancelBtn() {
return (
<Form.Btn type={ this.props.closeBtnType || 'secondary-outline' }
size={ this.props.closeBtnSize || 'lg' }
key="cancelBtn"
onClick={ this.props.closeBtnAction ? this.doCloseAction.bind(this) : this.close.bind(this) }
>{ this.props.closeBtnText || 'Cancel' }</Form.Btn>
);
}
不确定。只需要快速解释一下。
二元和三元运算符
您在第一个示例中看到的是使用逻辑 'AND' 运算符 &&
的二元短路求值表达式。 参见:Logical Operators - JavaScript | MDN
在第二个示例中,您有一系列使用逻辑 'OR' 运算符 ||
的二元短路求值表达式,然后是使用三元运算符 ?
的条件求值:
。 参见:Conditional (ternary) Operator - JavaScript | MDN
这些都不是 ReactJS 原生的,但它们非常适合在 JSX 中使用,因为它们是可以计算的表达式 "inline",而像 if
-else
这样的语句除非放置在 immediately-invoked function expression or moved out of the JSX markup. See: If-Else in JSX | React
另请参阅:
{ this.props.footerLinkText && getFooterLink.call(this) }
这是一个Short-Circuit Evaluation。意思是如果this.props.footerLinkText
为真,getFooterLink
就会被执行。
{ this.props.closeBtnText || 'Cancel' }
如果 this.props.closeBtnText
为真,则返回 Cancel
。结果会显示Cancel