通过布尔短路查看控件
View control through boolean short-circuiting
我在学习 React Native 的时候遇到过这样一个例子:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
showView: true,
}
}
removeView(){
this.setState({
showView: false,
});
}
render(){
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{this.state.showView && (
<View style={{backgroundColor: 'red', height: 100, width: 100 }}> // View to be removed
<TouchableHighlight onPress={() => this.removeView()}>
<Text>Remove View</Text>
</TouchableHighlight>
</View>
)}
</View>
)
}
}
我不明白的是为什么this.state.showView
可以这样控制View,我确定肯定和布尔短路有关,但是我觉得括号里的内容应该评估为布尔值,所以我应该只能在组件上获得 true/false 值,而不是查看视图的内容。有人可以解释一下它为什么有效吗?
根据 React 文档:
It works because in JavaScript, true && expression
always evaluates to
expression
, and false && expression
always evaluates to false
.
Therefore, if the condition is true
, the element right after &&
will
appear in the output. If it is false
, React will ignore and skip it.
我在学习 React Native 的时候遇到过这样一个例子:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
showView: true,
}
}
removeView(){
this.setState({
showView: false,
});
}
render(){
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{this.state.showView && (
<View style={{backgroundColor: 'red', height: 100, width: 100 }}> // View to be removed
<TouchableHighlight onPress={() => this.removeView()}>
<Text>Remove View</Text>
</TouchableHighlight>
</View>
)}
</View>
)
}
}
我不明白的是为什么this.state.showView
可以这样控制View,我确定肯定和布尔短路有关,但是我觉得括号里的内容应该评估为布尔值,所以我应该只能在组件上获得 true/false 值,而不是查看视图的内容。有人可以解释一下它为什么有效吗?
根据 React 文档:
It works because in JavaScript,
true && expression
always evaluates toexpression
, andfalse && expression
always evaluates tofalse
.Therefore, if the condition is
true
, the element right after&&
will appear in the output. If it isfalse
, React will ignore and skip it.