Why do I need to use a constructor to create my style variable?

Asked

Viewed 121 times

0

import React, {Component} from 'react';
import {StyleSheet, TouchableOpacity, Text, View} from 'react-native';


class Botao extends Component{

this.style = StyleSheet.create({}); // ESSE CODIGO TA PEDINDO PARA CRIAR UM CONSTRUTOR

render(){
    return(
        <TouchableOpacity>
            <View>
                <Text>Clique</Text>
            </View>
        </TouchableOpacity>
    );
  }
}
export default class App extends Component{
render() {
    return (
        <View>
            <Botao/>
        </View>
    );
  }
}
  • I believe outside the construtor It’s really not a good idea to use the this, but the documentation talks about how you can create your style and import. https://facebook.github.io/create-react-app/docs/adding-a-stylesheet

2 answers

0

The constructor is prompted because it is not possible to declare variables with the keyword this out of the same, therefore, the method constructor is a special type of method for creating and starting variables, objects, class methods.

Implement the code below and it should work.

constructor() {
    this.style = StyleSheet.create({});
}
  • Got it! In case, does this not have the global class reference without the constructor? So can I take this and create the normal variable not? I just don’t understand why I need to make the statements inside the builder.

  • Yes, you can create the style variable outside the scope of the class as shown in the documentation link.

0

Couldn’t I do so? Without the builder...

class Botao extends Component{

    render(){
        return(
           <TouchableOpacity>
                <View>
                    <Text style={this.styles.texto}>Clique</Text>
                </View>
           </TouchableOpacity>
        );
    }

    styles = StyleSheet.create({
        texto:{
            fontSize: 60
        }
    }); 

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.