'&&'操作符用{this.props.children &&React.cloneElement (t
What does '&&' operator indicate with { this.props.children && React.cloneElement(this.props.children, { foo:this.foo})
我有一个使用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>
然后Child1
和Child2
将被渲染额外的道具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})
,但它包含在您的示例中是为了说明没有要呈现的子组件的情况。
- React重新渲染但未显示正确的组件
- React组件等待所需道具进行渲染
- React中的数据集表示
- Webpack开发服务器和React服务器端渲染
- React Redux错误页面管理
- react.js中的密钥绑定
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React:按键的性能提升
- 如何在react js中从一个页面导航到另一个页面
- React组件-设置页面标题
- 为react组件传递道具的最佳方式
- 如何使用带有Preact的React路由器
- React.cloneElement:传递新的孩子或复制props.children
- React.cloneElement / HOC / Transclusion
- 在 React.cloneElement() 中覆盖 props 时出错
- React createElement vs cloneElement
- React.cloneElement->添加className元素
- '&&'操作符用{this.props.children &&React.cloneElement (t
- React, "this", cloneElement and es6