简体   繁体   English

React-Native将var添加到视图标签

[英]React-Native add var into view tag

I have this class containing a string and the variable: 我有一个包含字符串和变量的类:

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

However, I'm getting this error 但是,我收到此错误

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

Is there any way I can get the class to return both the text and the variable when used? 有什么办法可以使类在使用时返回文本和变量?

<Number/>

In ES6 (the way you declared your class), you can't declare variables the way you want to. 在ES6(声明类的方式)中,无法以所需的方式声明变量。 Here is explanation ES6 class variable alternatives 这是解释ES6类变量的替代方法

What you can do is to add it inside constructor, or inside render method. 您可以做的是将其添加到构造函数或render方法中。

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                 
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM