是否需要JavaScript / React的构造方法?

wes*_*sif 0 javascript reactjs react-native

此代码需要构造函数。我不理解需要使用构造函数来使用“ this”的必要性(Eunãoestou entendendo必需的构造函数para usar或“ 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>
    );
}
  }
Run Code Online (Sandbox Code Playgroud)

我可以不使用它而这样做吗?

class Botao extends Component{

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

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

}
Run Code Online (Sandbox Code Playgroud)

Wil*_*ins 6

您实际上在这里有两个选择...

1)使用类构造函数:

class Botao extends Component{

  constructor(){
   this.styles = StyleSheet.create({}); // requiring a constructor
  }

  render(){
    return(
        <TouchableOpacity>
            <View>
                <Text>Clique</Text>
            </View>
        </TouchableOpacity>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

2)将其直接声明为类属性(不带this):

class Botao extends Component{

  styles = StyleSheet.create({});

  render(){
    return(
        <TouchableOpacity>
            <View>
                <Text>Clique</Text>
            </View>
        </TouchableOpacity>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,您都可以styles使用this.styles

如果要编写React组件,通常不需要使用构造方法。就像在文档中说的那样:

如果您不初始化状态并且不绑定方法,则无需为React组件实现构造函数。

  • 请注意,第二个选项使用的语法不是标准javascript的一部分,因此需要使用babel的plugins-proposal-class-properties。React应用程序通常使用此插件。第二种方式编写代码会转换为第一种方式。 (2认同)