2017-10-19 148 views
0

我正在使用一個簡單的演示來學習反應原生,我發現了一個奇怪的事情。反應原生不能在組件狀態使用布爾值

這是我的代碼:

export default class App extends Component { 

    constructor(props) { 
    super(props) 
    this.state = {success: false} 
    } 

    render() { 
    return (
     <View style={styles.container}> 
     <Text style={styles.welcome}> 
      Welcome to React Native! 
     </Text> 
     <Text style={styles.instructions}> 
      To get started, edit App.js. 
      {this.state.success}  //this line can not be shown 
     </Text> 
     <Text style={styles.instructions}> 
      {instructions} 
     </Text> 
     </View> 
    ); 
    } 
} 

我用設置的狀態在constructor()render()不能訪問它,當我success值設置爲一個字符串或整型,它就會顯示出來。

我的代碼有什麼問題嗎?爲什麼我不能使用布爾值?

+2

默認情況下,布爾值不會顯示在React中。爲什麼你需要顯示一個布爾值? – mersocarlin

+1

你期望看到什麼?字符串'false'? –

+1

未定義或空值不會顯示任何,順便說一句。您可以使用此屬性進行條件呈現。 – JulienD

回答

2

您正在訪問它,但沒有顯示任何內容,因爲它是一個布爾值,而不是字符串或數字。

如果你想顯示文字「真」或「假」,你應該首先與toString()轉換爲字符串:

<Text style={styles.instructions}> 
    To get started, edit App.js. 
    {this.state.success.toString()} 
</Text> 

如果我沒有記錯,我看書上說,他們決定不再渲染布爾值以支持更靈活的內聯條件。

短路評價是這樣一個例子:

{!this.state.success && <p>Whoops, something went wrong!</p>} 

success如果是真實的,上述消息將不被呈現。然而,在香草JS中,這將返回字符串字面值「false」 - 當例如您想要渲染時不理想。

想象那將是多麼煩人的是,如果你呈現一些對象方法的返回值(即indexOf()map()等)和應對提供的字符串字面未定義和其他falsy值。這不會發生;相反,React不呈現任何東西。

從官方文檔here一些更多的信息:

falsenullundefinedtrue是有效的兒童。他們根本不渲染。這些JSX表達式都將呈現相同的結果: