Reputation: 47
This code is requiring a constructor. I'm not understanding the need to have a constructor to use the 'this' (Eu não estou entendendo a necessidade de ter um construtor para usar o 'this')
import React, {Component} from 'react';
import {StyleSheet, TouchableOpacity, Text, View} from 'react-native';
class Botao extends Component{
this.styles = StyleSheet.create({}); // requiring a constructor
render(){
return(
<TouchableOpacity>
<View>
<Text>Clique</Text>
</View>
</TouchableOpacity>
);
}
}
can I do it this way without using it?
class Botao extends Component{
render(){
return(
<TouchableOpacity>
<View>
<Text style={this.styles.texto}>Clique</Text>
</View>
</TouchableOpacity>
);
}
styles = StyleSheet.create({
texto:{
fontSize: 60
}
});
}
Upvotes: 0
Views: 110
Reputation: 9787
You actually have two options here...
1) Use the class constructor:
class Botao extends Component{
constructor(){
this.styles = StyleSheet.create({}); // requiring a constructor
}
render(){
return(
<TouchableOpacity>
<View>
<Text>Clique</Text>
</View>
</TouchableOpacity>
);
}
}
2) Declare it directly as a class property (without this
):
class Botao extends Component{
styles = StyleSheet.create({});
render(){
return(
<TouchableOpacity>
<View>
<Text>Clique</Text>
</View>
</TouchableOpacity>
);
}
}
In both cases, you would access styles
from elsewhere in your class using this.styles
If you're writing a React component, you usually don't need to use the constructor method. As it says in the docs:
If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.
Upvotes: 6