简体   繁体   中英

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. Here is explanation ES6 class variable alternatives

What you can do is to add it inside constructor, or inside render method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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