TypeScript React Native Flatlist:如何为 renderItem 赋予其项目的正确类型?

新手上路,请多包涵

我正在使用 TypeScript 构建一个 React Native 应用程序。 renderItem 抱怨解构的项目隐含地有一个 any 类型。我用谷歌搜索并找到 了这个问题,并尝试结合 React Native 的 @types 包中的 index.d.ts 中的类型来实现他们在这里教授的内容。

 export interface Props {
  emotions: Emotion[];
}

class EmotionsPicker extends PureComponent<Props> {
  keyExtractor = (item, index) => index;
  renderItem = ({ item }) => (
    <ListItem title={item.name} checkmark={item.checked} />
  );

  render() {
    return (
      <FlatList<Emotion>
        keyExtractor={this.keyExtractor}
        renderItem={this.renderItem}
        data={this.props.emotions}
      />
    );
  }
}

不幸的是,这不起作用。我怎样才能给项目类型 Emotion

原文由 J. Hesters 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

我知道这是一个老问题,但人们在谷歌上搜索它可能仍然会欣赏它。

 import { FlatList, ListRenderItem } from 'react-native'
/*
.
.
.
*/
  renderItem: ListRenderItem<Emoticon> = ({ item }) => (
    <ListItem title={item.name} checkmark={item.checked} />
  );

原文由 Yhozen 发布,翻译遵循 CC BY-SA 4.0 许可协议

我找到了一个解决方案(虽然我不知道它是否理想):

 renderItem = ({ item }: { item: Emotion }) => (
  <ListItem title={item.name} checkmark={item.chosen} />
);

原文由 J. Hesters 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题