如果您正在使用流程并希望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',
},
})