[英]Constructor inside React component
I am completely new to react native, Can you some one fix the following code. 我本机反应是全新的,您能解决以下代码吗?
Iam using a view inside const and i need to use constructor inside the const function 我在const内部使用视图,我需要在const函数内部使用构造函数
const { width } = Dimensions.get('window');
const tileWidth = width - 30;
const tileHeight = tileWidth * 0.50;
const tileHeight = tileWidth * 0.50;
constructor(props) {
super(props);
this.state = {
//tileViewWidth: null,
tileViewHeight: null,
}
this.measureView = this.measureView.bind(this);
}
measureView(event) {
// console.log('event properties: ', event);
this.setState({
//tileViewWidth: event.nativeEvent.layout.width,
tileViewHeight: (event.nativeEvent.layout.height / 2) - 7,
});
}
const MyNavScreen = ({ navigation, banner }) => (
<ScrollView style={styles.container} >
<View style={css.home_tiles.container} onLayout={(event) => this.measureView(event)}>
<TouchableOpacity underlayColor="transparent" style={[{ width: tileWidth, height: this.state.tileViewHeight }]}> </TouchableOpacity> </View>);
You are trying to add a state to the stateless component. 您试图将状态添加到无状态组件。 You can find many articles about their differences(for example this one). 您可以找到许多有关它们之间差异的文章(例如, 这篇文章)。 Use regular component instead of stateless component: 使用常规组件而不是无状态组件:
class GeneralButton extends Component {
constructor(props) {
super(props)
this.state = {
//tileViewWidth: null,
tileViewHeight: null,
}
this.measureView = this.measureView.bind(this)
}
measureView(event) {
// console.log('event properties: ', event);
this.setState({
//tileViewWidth: event.nativeEvent.layout.width,
tileViewHeight: (event.nativeEvent.layout.height / 2) - 7,
})
}
render() {
return <ScrollView style={styles.container}>
<View style={css.home_tiles.container} onLayout={(event) => this.measureView(event)}>
<TouchableOpacity underlayColor="transparent" style={[{width: tileWidth, height: this.state.tileViewHeight}]}>
</TouchableOpacity>
</View>
</ScrollView>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.