在内部定义函数的属性类型的功能组件和类组件之间有什么区别?
例如,
在类组件中,没有问题。
class ListView extends React.Component {
...
renderItem: SectionListRenderItem<Circle> = ({ item }) => { // no lint warning
const { circleStore } = this.props
return (
<CircleList
hideButton
title={item.title}
desc={item.desc}
iconSource={{ uri: item.logoImageUrl }}
onPress={() => circleStore && circleStore.setCurrentCircle(item)}
></CircleList>
)
}
render() {
return (
<SectionListView ... />
)
}
}
...
在功能组件中,它使'item' is missing in props validation - eslint(react/prop-types)
成为如下问题。
...
const ListView = (props: Props) => {
const renderItem: SectionListRenderItem<Circle> = ({ item }) => ( // lint warning
<CircleList
hideButton
title={item.title}
desc={item.desc}
iconSource={{ uri: item.logoImageUrl }}
onPress={() => {}}
></CircleList>
)
...
return (
<SectionListView ... />
)
}
...
可以通过以下代码进行固定
const renderItem: SectionListRenderItem<Circle> = ({ item }) => (
更改为
const renderItem: SectionListRenderItem<Circle> = ({ item }: { item: Circle }) => (
Circle
是我声明的接口。
我想知道为什么会这样,有什么区别。
与类组件相比,无状态组件中只有renderItem
会产生皮棉错误。
interface Props {
popularCircles: Circle[]
recentCircles: Circle[]
onPressSection?: (section: Circle) => void
onPressCircle?: (circle: Circle) => void
}
export const Main = ({
popularCircles,
recentCircles,
onPressCircle,
}: Props) => {
const renderSectionHeader = ({ section: { title } }: SectionHeader) => {
return (
<SectionHeaderCell
title={title}
buttonTitle={''}
disabled
></SectionHeaderCell>
)
}
const renderItem: SectionListRenderItem<Circle> = ({
item,
}) => ( // This line makes a eslint warning only in functional component.
<CircleList
hideButton
title={item.title}
desc={item.desc}
iconSource={{ uri: item.logoImageUrl }}
onPress={() => onPressCircle && onPressCircle(item)}
></CircleList>
)
return (
<Container>
<SectionList
sections={[
{
title: 'Title1',
data: popularCircles,
},
{
title: 'Title2',
data: recentCircles,
},
]}
renderSectionHeader={renderSectionHeader}
renderItem={renderItem}
keyExtractor={(item, index) => item + index}
contentContainerStyle={{ flex: 1 }}
/>
</Container>
)
}
export default Main
Circle.d.ts
export interface Circle {
circleId: number
title: string
desc: string
logoImageUrl?: string
}