Если вы используете поток и хотите установить 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',
},
})
Можете ли вы опубликовать другие функции? – QoP