首页 > 解决方案 > 为什么函数作为 React child 无效?

问题描述

我正在尝试将基于类的组件转换为功能性(无状态)组件。每次我都会收到此错误:

函数作为 React 子级无效。如果您返回 Component 而不是 ...

这是我的组件:

 const ProfileStories = (props) => {
  const renderStory = () => {
    const data = props.userStory ? props.userStory.data : [];
    if (props.isClicked) {
      return (
        <FlatList
          data={data}
          renderItem={renderStoryItem}
          keyExtractor={(item, index) => index.toString()}
          numColumns={2}
        />
      );
    } return null;
  };

  const renderStoryItem = (item) => {
    return (
      <StoryItem
        key={item.id}
        content={item.content}
        date={item.createdAt}
      />
    );
  };

  return (
    <CenterView>
      {renderStory}
    </CenterView>
  );
};

export default ProfileStories;

标签: reactjsreact-native

解决方案


这里:

return (
  <CenterView>
    {renderStory}
  </CenterView>
);

您正在传递 renderStory,这确实是一个函数。您可能打算将 renderStory 函数的结果作为子函数传递给 CenterView,如下所示:

return (
  <CenterView>
    {renderStory()}
  </CenterView>
);

推荐阅读