【问题标题】:View control through boolean short-circuiting通过布尔短路查看控制
【发布时间】:2018-01-06 00:03:53
【问题描述】:

我在学习 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>
    )
  }
}

我不明白为什么 View 可以由this.state.showView 控制这种方式,我确信它肯定与布尔短路有关,但我认为括号中的内容应该评估为布尔值,所以我应该只能在组件上设置真/假值,而不是查看视图的内容。有人可以解释一下它为什么起作用吗?

【问题讨论】:

    标签: reactjs react-native short-circuiting


    【解决方案1】:

    根据 React 文档:

    之所以有效,是因为在 JavaScript 中,true &amp;&amp; expression 总是计算为 expressionfalse &amp;&amp; expression 始终计算为 false

    因此,如果条件为true,则&amp;&amp; 之后的元素将 出现在输出中。如果是false,React 会忽略并跳过它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2014-03-23
      • 2012-10-25
      • 2015-04-10
      • 1970-01-01
      相关资源
      最近更新 更多