【问题标题】:No overload matches on FlatList React NativeFlatList React Native 上没有重载匹配
【发布时间】:2021-09-22 05:28:52
【问题描述】:

我正在使用 React Native 处理我的 <FlatList>

我有 ff flatlist 代码:

<FlatList
            data={this.state.books}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({item}: {item: any}, index: number) =>
              this.renderItem(item, index)
            }
            ListEmptyComponent={
              <View style={styles.listEmpty}>
                <Text style={styles.emptyText}>Not Reading any books</Text>
              </View>
            }

然后在我的 renderItem 函数中:

 renderItem = (item: string, index: number) => (
    <View style={styles.renderContainer}>
      <View style={{flex: 1, justifyContent: 'center', paddingLeft: 10}}>
        <Text>{item}</Text>
      </View>

      <TouchableOpacity onPress={() => console.log('hello')}>
        <View style={styles.btnMarkRead}>
          <Text style={{fontWeight: 'bold', color: 'black'}}>Mark as Read</Text>
        </View>
      </TouchableOpacity>
    </View>
  );

我的打字稿代码在我的 FlatList 声明中突出显示了 renderItem 这个词,它说:

No overload matches this call.
  Overload 1 of 2, '(props: FlatListProps<String> | Readonly<FlatListProps<String>>): FlatList<String>', gave the following error.
    Type '({ item }: { item: any; }, index: number) => JSX.Element' is not assignable to type 'ListRenderItem<String>'.
  Overload 2 of 2, '(props: FlatListProps<String>, context: any): FlatList<String>', gave the following error.

我有 ff 状态:

this.state = {
  totalCount: 0,
  readingCount: 0,
  doneCount: 0,
  isAddNewBookVisible: false,
  textInputData: '',
  books: [],
};

如何解决高亮错误?

【问题讨论】:

标签: javascript typescript react-native


【解决方案1】:

使用

({item, index}) => this.renderItem(item, index)
    

如果您想参考下面的示例,请为传递给 Flatlist 的数据提供类型

import React from 'react';
import {FlatList, View} from 'react-native';

interface PropsInterface {}

interface StateInterface {
  books?: any[];
}

class ComponentName extends React.Component<PropsInterface, StateInterface> {
  constructor(props: PropsInterface) {
    super(props);

    this.state = {
      books: [],
    };
  }

  renderItem = (item: any, index: number) => {
    return <View></View>;
  };

  render() {
    return (
      <FlatList
        data={this.state.books}
        renderItem={({item, index}) => this.renderItem(item, index)}
      />
    );
  }
}

【讨论】:

  • 我正在使用打字稿。所以它抱怨像Binding element 'item' implicitly has an 'any' type.ts(7031) 这样的类型,如果我只会这样做的话
  • 为传递给 FlatList 的数据指定类型。我将更新示例
猜你喜欢
  • 2021-11-03
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2019-08-13
相关资源
最近更新 更多