此代码需要构造函数。 我不理解是否需要使用“ this”的构造函数 (Eunãoestou entendendo成为必需的“ this 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
}
});
}
答案 0 :(得分:6)
您实际上在这里有两个选择...
1)使用类构造函数:
class Botao extends Component{
constructor(){
this.styles = StyleSheet.create({}); // requiring a constructor
}
render(){
return(
<TouchableOpacity>
<View>
<Text>Clique</Text>
</View>
</TouchableOpacity>
);
}
}
2)直接将其声明为类属性(无this
):
class Botao extends Component{
styles = StyleSheet.create({});
render(){
return(
<TouchableOpacity>
<View>
<Text>Clique</Text>
</View>
</TouchableOpacity>
);
}
}
在两种情况下,您都可以使用styles
this.styles
如果要编写React组件,通常不需要使用构造方法。如the docs中所述:
如果您不初始化状态并且不绑定方法,则无需为React组件实现构造函数。