2017-04-17 122 views
0

我有这样的反应成分,我创建了一个常量见下文:阵营组件this.variable不渲染

export class MyComponent extends React.Component { 
    constructor() { 
    super(); 
    const mytext = 'Some Text'; 
    } 

    render() { 
    return (
     <div> 
     {this.mytext} 
     </div> 

    ); 
    } 
} 

这个常量不渲染mytext的,当我使用{} this.mytext

什么我是我做错了?

+1

'const this.mytext ='Some Text';''''mytext}'......! – Jai

+0

mytext的数据类型是const。所以你需要将{this.mytext}改为{mytext} – Ved

+0

@Jai我认为const this this.mytext ='Some Text';是错误的语法。 – Ved

回答

2

{this.mytext}应该{mytext}

如果你想声明类型常量比你需要定义它像这样

const mytext = 'Some Text'; 
    export class MyComponent extends React.Component { 
     constructor() { 
     super(); 

     } 

    render() { 
     return (
      <div> 
      {mytext} 
      </div> 

     ); 
     } 

编辑1.更好approcah申报的全局变量全局变量可以是:

export class MyComponent extends React.Component { 
     constructor() { 
     super(); 
     this.mytext = "VED"//you can use it now anywhere inside your file 
     } 
+0

所以我不能在组件内定义变量? – JakeBrown777

+0

不可以。您可以定义像this.mytext,但不能const mytext。 – Ved