2017-07-03 39 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