如果您正在使用flow并希望this.state
在组件中设置constructor
:
1.创建type
一个this.state
type State = { width: number, height: number }
2.用那个初始化你的组件type
export default class MyComponent extends Component<Props, State> { ... }
3.现在您可以设置this.state
没有任何流量错误
constructor(props: any) {
super(props)
this.state = { width: 0, height: 0 }
}
这是一个更完整的示例,它在调用this.state
时更新组件的宽度和高度。onLayout
// @flow
import React, {Component} from 'react'
import {View} from 'react-native'
type Props = {
someNumber: number,
someBool: boolean,
someFxn: () => any,
}
type State = {
width: number,
height: number,
}
export default class MyComponent extends Component<Props, State> {
constructor(props: any) {
super(props)
this.state = {
width: 0,
height: 0,
}
}
render() {
const onLayout = (event) => {
const {x, y, width, height} = event.nativeEvent.layout
this.setState({
...this.state,
width: width,
width: height,
})
}
return (
<View style={styles.container} onLayout={onLayout}>
...
</View>
)
}
}
const styles = StyleSheet.create({
container: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
})