代码之家  ›  专栏  ›  技术社区  ›  Conor Watson

在React Native中使用渲染道具

  •  0
  • Conor Watson  · 技术社区  · 7 年前

    我正在开发一个React本机组件,该组件应该用作“选择”选择器,显示 FlatList 扁平列表 为了可自定义,本质上我希望将自定义渲染函数传递给 SelectPicker 将负责呈现列表项的组件。

    StandardPicker 组件I有一个渲染函数,如下所示:

    render() {
      const { range } = this.props;
      return (
        <View style={styles.modal}>
          <FlatList
            data={range}
            renderItem={this.renderListItem}
          />
        </View>
      );
    }
    

    renderListItem

    renderListItem({ item, index }) {
      const { onSelectItem, renderItem } = this.props;
    
      const renderedItem = renderItem ? (
        renderItem()
      ) : null
    
      return (
        <TouchableNative
          key={index}
          onPress={() => {
            onSelectItem(index);
          }}
        >
          {renderedItem}
        </TouchableNative>
      );
    }
    

    现在,我在另一个组件中渲染 然后像这样传递一个渲染函数

    renderCustomItem() {
      return (
        <View>
          <Text>Testing</Text>
          <Text>Test 2</Text>
        </View>
      );
    }
    
    <StandardPicker
      range={this.listItems}
      onSelectItem={item=>
        this.setState({ selectedItem: item})
      }
      renderItem={this.renderCustomItem}
    />
    

    然而,我最终得到了一个错误 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

    1 回复  |  直到 7 年前
        1
  •  1
  •   Michael Ostrovsky    7 年前

    感觉这比你需要的要复杂得多,你完全可以将渲染函数传递给组件,但只传递主体要容易得多,现在你得到的错误似乎是某种导入/拼写错误,因为你正在使用的一个对象实际上正如代码所说, undefined 现在,我需要更好地查看您的代码,以找出它发生的确切位置,但无论哪种方式,您都可以随意缩短您的函数,如下所示:

    renderListItem({ item, index }) {
      const { onSelectItem, renderItem } = this.props;
    
      return (
        <TouchableNative
          key={index}
          onPress={() => {
            onSelectItem(index);
          }}
        >
          {renderItem}
        </TouchableNative>
      );
    }
    

    就好像它是未定义的一样,JSX不会以任何方式呈现任何内容。

    推荐文章