React-Native如何使用布尔值

时间:2017-03-22 17:57:09

标签: javascript react-native boolean

我很反应原生,我有一个非常基本的问题。 遗憾的是,我不知道如何在React-Native中使用布尔值。 我试图在谷歌上找到一个解决方案,但显然我的问题很简单,没有人问过它。

在我的代码中,我必须声明布尔值吗?

如何更改值?

比较它的正确方法是什么? (我想如果(myBoolean === true)但我不完全确定。)

我很想用这个愚蠢的问题打扰你们,

问候,

迈克尔

2 个答案:

答案 0 :(得分:4)

This is more a JS question than an React Native one, since React Native uses standard-compliant JavaScript as programming language. So, going through all your questions:

Where in my code do I have to declare the boolean?

The boolean is one of the 6 data type primitives in JS, along with null, undefined, number, string and Symbol (ES6 only). So you can just create a boolean the way you would with any of those. For instance:

var myBoolean = true;

You can create the boolean in pretty much any part of your code: inside a function, as a global variable, as an object property...

Remember than JS is a dynamically weakly typed language, which means that if you assign a different type value to myBoolean, it would then be of that type. For instance:

var myBoolean = true; // I'm a boolean
myBoolean = "A string"; // I'm a string

How can I change the value?

We just changed its value by initializing the variable, but it would be as simple as:

var myBoolean = true; // I'm a boolean
myBoolean = false;

What is the right way to compare it ? (I think if(myBoolean===true) but I am not completely sure.)

Your approach is totally correct, but you can also do some other things in this case. This are all valid:

if(myBoolean === true) // Will check that myBoolean has the same value and type as true 
if(myBoolean == true) // Will check that myBoolean has the same value as true
if(myBoolean) // Will check that myBoolean has a 'truthy' value (anything that is not a false, 0, "", null, undefined or NaN (not a number).

答案 1 :(得分:2)

martinarroyo的答案很棒,但只是补充:

React Native使用 JSX (XML + JavaScript)。

使用 JSX 时,始终将大括号括在大括号中:

<View>
  <MapView
    showsUserLocation={true}
  >
  </Mapview>
</View>

您也可以使用 JSX 做一些有趣的事情,比如有条件渲染组件:

<View>
  // This component will render
  <TouchableHighlight>
    {true}
  </TouchableHighlight>
  // This component will not render
  <TouchableHighlight>
    {false}
  </TouchableHighlight>
</View>

更多信息: https://facebook.github.io/react/docs/jsx-in-depth.html