Nếu bạn đang sử dụng dòng và muốn thiết lập this.state
trong của constructor
thành phần của bạn:
1. Tạo type
cho this.state
type State = { width: number, height: number }
2. Khởi tạo thành phần của bạn với điều đó type
export default class MyComponent extends Component<Props, State> { ... }
3. Bây giờ bạn có thể đặt this.state
mà không cần bất kỳ dòng lỗi
constructor(props: any) {
super(props)
this.state = { width: 0, height: 0 }
}
Dưới đây là một nhiều com ví dụ plete cập nhật this.state
với chiều rộng và chiều cao của thành phần khi gọi 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',
},
})
Nguồn
2017-12-01 23:49:11
bạn có thể đăng các chức năng khác không? – QoP