我是全新的反应原生, 你能解决以下代码吗?
我在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>);
答案 0 :(得分:1)
您正在尝试向无状态组件添加状态。您可以找到许多有关其差异的文章(例如this一个)。使用常规组件而不是无状态组件:
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>
}
}