英文:
Typescript: Assign prop type to component prop in a custom component in React Native
问题
我正在创建一个自定义可重用组件,它可以接另一个组件作为属性,用作子元素。我想从传递给此组件的数据动态添加类型。
最佳参考是 <FlatList>
。我需要确切地了解如何创建 <FlatList>
。我们为它提供了一个 renderItem
属性,它将接受该组件并将 data
的类型传递给 renderItem
函数。
示例:
<FlatList
data={['str1', 'str2', 'str3']} // 这里数组的类型是 string[]
renderItem={({item}) => <Text>{item}</Text>} // item 的类型是 string
/>
期望的组件:
<MyComponent
data={[ { name: 'abc', age: 5 }, { name: 'xyz', age: 5 }] } // 数组是自定义类型 User[]
renderItem={({item}) => <Text>{item.name}</Text>} // item 的类型是 User
/>
英文:
I am creating a custom reusable component which can take in another Component as a prop to used as a children. I want to add the type dynamically form the data which is passed into this component.
The best reference is <FlatList>
. I need exactly how <FlatList>
is created. We have a renderItem
prop for it where it will take in that component and pass the data
's type to the renderItem
function.
Example:
<FlatList
data={['str1', 'str2', 'str3']} // Array type is string[] here
renderItem={({item}) => <Text>{item}</Text>} // The item type is string here />
Desired Component:
<MyComponent
data={[ { name: 'abc', age: 5 }, { name: 'xyz', age: 5 } ]} // Array is a custom type User[]
renderItem={({item}) => <Text>{item.name}</Text>} /> // The item is User type
答案1
得分: 1
FlatList
使用泛型参数来实现所需的结果。您可以创建一个使用相同机制的自定义组件。以下是一个示例:
type MyComponentProps<T> = {
data: T[]
renderItem: (item: T) => React.ReactNode
}
const MyComponent = <T>({ data, renderItem }: MyComponentProps<T>) => {
// 你的代码
}
希望这对你有所帮助。
英文:
FlatList
is using generic parameters to achieve the desired result. You can create a custom component that using the same mechanism. Here's an example:
type MyComponentProps<T> = {
data: T[]
renderItem: (item: T) => React.ReactNode
}
const MyComponent = <T,>({data, renderItem}: MyComponentProps<T>) => {
// you code
}
Hope it's helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论