2017-07-03 24 views
0

我對此很陌生,所以很可能這很簡單,但我無法理解它。 這是我簡單的例子:React原生意外令牌如果說明

export default class WhyScreen extends React.Component { 

constructor(props) { 
    super(props); 
    this.index = false; 
} 


if (this.index){ 
    console.log('ok'); 
} 

render() {  
    return (
     <View style={styles.parag}> 

     </View> 

    ); 
} 

如果取出if語句,我沒有得到任何錯誤。但是,一旦我放入if語句,就會在If語句的行上出現意外令牌錯誤。事實上,如果我測試一個條件,或者只是測試1 === 1,它確實會有所不同,但我仍然會遇到錯誤。很明顯,我錯過了一些東西。

回答

1

WhyScreen是一個類,所以您需要爲該代碼創建一個方法。或者如果你希望它在創建時運行,你可以把它放在構造函數中。

export default class WhyScreen extends React.Component { 

constructor(props) { 
    super(props); 
    this.index = false; 
    if (this.index) { 
    console.log('ok'); 
    } 
} 

testIndex =() => { 
    if (this.index){ 
     console.log('ok'); 
    } 
} 

render() {  
    return (
     <View style={styles.parag}> 

     </View> 

    ); 
} 
+0

謝謝..這是很有道理的。 – Allen