在 React Native 中将三元运算符与 useState 一起使用

use ternary operator with useState in React Native

我的代码中的三元运算符有问题

  1. 我 2 状态保持 true/false 关于何时按下按钮:

这里(抱歉,我在块代码中格式化它时遇到问题)

const [lineChecked, setLineChecked] = useState(false);
const [pieChecked, setPieChecked] = useState(false);

这是带有 onPress 的 Touchable Opacity,我指定将 1 状态变为真,将其他状态变为假(我有 2 个 - 另一个相反):

<TouchableOpacity
      onPress={() => {
        setPieChecked(true);
        setLineChecked(false);
      }}
    >

我想要完成的是,当我按下 1 个可触摸不透明度图形时,将显示 X,当我按下另一个可触摸不透明度时,将显示另一个图形,初始状态是 none 个图形已呈现。

这是我尝试过的:

 <View style={styles.graphsPart}>
    {lineChecked == "true" ? (
      <LineChart
        data={data}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
    {pieChecked == "true" ? (
      <LineChart
        data={dataTwo}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
  </View>

建议??

(true == 'true') === false

您需要比较布尔值 (true),而不是字符串 ('true')。

更好的是,您可以只检查一般真实性:

const val = true

const result = val ? 'yes' : 'no'
// if val is a boolean, this will work the same as
// `val === true ? 'yes' : 'no'`
 <View style={styles.graphsPart}>
    {lineChecked ? (
      <LineChart
        data={data}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
    {pieChecked ? (
      <LineChart
        data={dataTwo}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
  </View>

你需要检查那个不需要的值== 'true'