2017-06-10 32 views
1

我有一個包含字符串變量這個類:陣營本地VAR添加到視圖標籤

class Number extends Component{ 
    var num = 8 
    render(){ 
     return{ 
      <Text>The number is: </Text> + num 
     } 
    } 
} 

不過,我得到這個錯誤

Unexpected token (31:6) 
var num = 8 
    ^

有什麼辦法,我可以讓類在使用時返回文本和變量?

<Number/> 

回答

2

在ES6中(你聲明你的類的方式),你不能以你想要的方式聲明變量。這裏是解釋ES6 class variable alternatives

你可以做的是將它添加到構造函數或渲染方法內部。

class Number extends Component{ 
    constructor(props){ 
     super(props); 
     this.num = 8 // this is added as class property - option 1 
     this.state = { num: 8 } //this is added as a local state of react component - option 2 
    } 
    render(){ 
     const num = 8; // or here as regular variable. option 3 
     return{ 
      <Text>The number is: </Text> + this.num // for option 1 
      // <Text>The number is: </Text> + this.state.num //for option 2 
      // <Text>The number is: </Text> + num //for option 3     
     } 
    } 
} 
+0

我明白了,非常感謝! – iamacat