【问题标题】:What is the functionality of this React style expression?这个 React 风格表达式的功能是什么?
【发布时间】:2021-07-22 14:24:10
【问题描述】:
<Text
    style={[
        styles.buttonLabel,
        selectedValue === value && styles.selectedLabel,
    ]}
>{value}</Text>

以上是从react-native flexbox官方文档的第二个示例中提取的一段代码。谁能解释style prop 中表达式的功能?

【问题讨论】:

标签: javascript reactjs react-native


【解决方案1】:

基本上,style 需要一种样式(例如,具有widthbackground-color 等的对象)或样式数组。表达式selectedValue === value &amp;&amp; styles.selectedLabel 可以产生两个不同的值:

  • falseselectedValue !== value。毕竟false &amp;&amp; value 就是false
  • styles.selectedLabel 如果selectedValue === value

这导致styles 成为[styles.buttonLabel, false][styles.buttonLabel, styles.selectedLabel]。组合样式时,false 将被忽略。

基本上,这是在单个表达式中“如果条件匹配,则添加此额外样式”。

【讨论】:

  • 所以基本上它是 (selectedValue === value) && styles.selectedLabel 和 styles.selectedLabel 如果第一个表达式{在括号中}的计算结果为真,则有效。谢谢开尔文!!
  • @Snehalsingh 确实如此。当a &amp;&amp; b 中的a 为假时(undefinednullfalse""0),它会立即返回a,甚至无需评估b。这是非常基本的 JavaScript,你可以找到很多关于条件的教程。另外,在这里提问时,不要忘记将最有帮助的答案标记为解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
相关资源
最近更新 更多