Reputation:
I am trying to access a variable in the render method. I have declared the variable outside the render function but inside the class definition. For some reason I cannot access the variable. It works if I declare the variable inside the render function.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class HelloWorldApp extends Component {
let a = "Random"
render() {
return (
<View>
<Text>{a}</Text>
</View>
);
}
}
Upvotes: 0
Views: 993
Reputation: 3359
Set variable in state and access that using this
keyword this.state.a
or you have to define it before your class as a constant
or let
or var
.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
const a="random";
export default class HelloWorldApp extends Component {
constructor (props){
super (props);
this.state={
let a = "Random"
}
}
render() {
let {a}=this.state;
return (
<View>
<Text>{a}</Text>
</View>
);
}
}
Upvotes: 0
Reputation: 1646
You need to move your variable declaration into the render method. The declaration won't work otherwise.
render() {
const a = "Random";
return (
<View>
<Text>{a}</Text>
</View>
);
}
Upvotes: 1