【问题标题】:Why is react ternary operator only works in between tags?为什么反应三元运算符仅适用于标签之间?
【发布时间】:2020-05-07 05:21:20
【问题描述】:

在开发过程中,我一直在为 react native 中的一个非常简单的三元运算而摸不着头脑。我正在使用与eslint 集成的 prettier,但错误并没有太大帮助

它没有检测到我的三元运算

import { Ionicons, MaterialIcons } from "@expo/vector-icons";
import * as React from "react";
import React, {StyleSheet} from "react-native";
import Colors from "../constants/Colors";

const styles = StyleSheet.create({
  icons: {marginBottom: -3}
});

export default function TabBarIcon(props) {
  const {type, name, focused} = props;
    return (
    { type === "Ionicons" ?
    <Ionicons
    name={name}
    size={30}
    style={styles.icons}
    color={
      focused ? Colors.tabIconSelected : Colors.tabIconDefault
    }
  /> :
    <MaterialIcons
    name={name}
    size={30}
    style={icons}
    color={
      focused ? Colors.tabIconSelected : Colors.tabIconDefault
    }
    />
  }

    );
}

错误:

["ERROR" - 3:15:41 PM] Error formatting document.
["ERROR" - 3:15:41 PM] Unexpected token, expected "," (13:12)
  11 |   const {type, name, focused} = props;
  12 |  return (
> 13 |     { type === "Ionicons" ?
     |            ^
  14 |     <Ionicons
  15 |     name={name}
  16 |     size={30}

然后经过反复试验,将它们放在 React 片段之间似乎可行。对此有什么解释吗?我似乎在文档中找不到任何内容。

export default function TabBarIcon(props) {
    const { type, name, focused } = props;
    return (
        <>
            {type === "Ionicons" ? (
                <Ionicons
                    name={name}
                    size={30}
                    style={styles.icons}
                    color={
                        focused ? Colors.tabIconSelected : Colors.tabIconDefault
                    }
                />
            ) : (
                <MaterialIcons
                    name={name}
                    size={30}
                    style={icons}
                    color={
                        focused ? Colors.tabIconSelected : Colors.tabIconDefault
                    }
                />
            )}
        </>
    );
}

【问题讨论】:

  • 这能回答你的问题吗? Ternary operator in react native
  • 显然不是因为我的标签不是开始标签
  • 我改变了我的问题,因为它的行为不同。我进一步解释了

标签: reactjs react-native


【解决方案1】:

大括号语法仅适用于您想在 JSX 中使用一些 JS 表达式时。 在您上面的代码中,这是一个语法错误。正确的语法应该是这样的

export default function TabBarIcon(props) {
  const { type, name, focused } = props
  return type === 'Ionicons' ? (
    <Ionicons
      name={name}
      size={30}
      style={styles.icons}
      color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
    />
  ) : (
    <MaterialIcons
      name={name}
      size={30}
      style={icons}
      color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
    />
  )
}

【讨论】:

  • 我可以看到这应该有什么帮助,在寻找重复项之前要发表评论以尝试,可能会很好地添加更多描述为什么,至少他们知道如何称呼它并寻找了解更多:)
猜你喜欢
  • 2017-11-13
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2018-04-11
  • 2020-07-16
  • 2018-01-26
  • 2014-01-21
相关资源
最近更新 更多