Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否需要JavaScript/React中的构造函数?_Javascript_Reactjs_React Native - Fatal编程技术网

是否需要JavaScript/React中的构造函数?

是否需要JavaScript/React中的构造函数?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,此代码需要一个构造函数。 我不理解需要一个构造函数来使用“this” 欧盟必须为“这一点”制定必要的解释 import React, {Component} from 'react'; import {StyleSheet, TouchableOpacity, Text, View} from 'react-native'; class Botao extends Component{ this.styles = StyleSheet.create({}); // requiring a

此代码需要一个构造函数。 我不理解需要一个构造函数来使用“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>
    );
}
  }
我可以不用它就这样做吗

class Botao extends Component{

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

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

}

你实际上有两个选择

1使用类构造函数:

class Botao extends Component{

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

  render(){
    return(
        <TouchableOpacity>
            <View>
                <Text>Clique</Text>
            </View>
        </TouchableOpacity>
    );
  }
}
在这两种情况下,您都可以使用this.styles从类中的其他位置访问样式

如果要编写React组件,通常不需要使用构造函数方法。正如书中所说:

如果不初始化状态,也不绑定方法,则不需要为React组件实现构造函数


是的,第二种方法是如何做。声明这样的样式使它成为一个类属性,可以从类中的其他地方访问。在第一种情况下,构造函数的角色是什么?请注意,第二个选项使用的语法还不是标准javascript的一部分,因此需要使用babel的插件建议类属性。React应用程序通常使用此插件。以第二种方式编写代码会转换为第一种方式。如果没有构造函数,“this”不会假定全局范围?@wesif我用更多信息更新了我的答案-简而言之,它没有任何用处。这在两种情况下都具有全局作用域,但如果选择在构造函数中附加styles属性,则必须使用它才能将其附加到包含的类。在构造之前,没有实例,因此这没有任何意义。这有用吗?
class Botao extends Component{

  styles = StyleSheet.create({});

  render(){
    return(
        <TouchableOpacity>
            <View>
                <Text>Clique</Text>
            </View>
        </TouchableOpacity>
    );
  }
}