gpt4 book ai didi

javascript - React 组件内的构造函数

转载 作者:行者123 更新时间:2023-12-03 03:57:16 25 4
gpt4 key购买 nike

我对原生 react 完全陌生,您能修复以下代码吗?

我在 const 内部使用 View ,并且我需要在 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>);

最佳答案

您正在尝试向无状态组件添加状态。您可以找到很多关于它们差异的文章(例如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>
}
}

关于javascript - React 组件内的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44888757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com